Spaces:
Sleeping
Sleeping
Commit ·
d32e728
1
Parent(s): d5ec07c
Add file
Browse filesFiles changed (47)
- .gitignoreAdded+31
- README.md+284
- backend/.env.exampleAdded+3
- backend/DockerfileAdded+12
- backend/api/api/__init__.pyAdded
- backend/api/api/asgi.pyAdded+16
- backend/api/api/settings.pyAdded+112
- backend/api/api/urls.pyAdded+30
- backend/api/api/wsgi.pyAdded+16
- backend/api/app.logAdded
- backend/api/manage.pyAdded+22
- backend/api/models/README.mdAdded+7
- backend/api/models/pytorch_model.pthAdded+3
- backend/api/notifications/__init__.pyAdded
- backend/api/notifications/admin.pyAdded+3
- backend/api/notifications/api_views.pyAdded+218
- backend/api/notifications/apps.pyAdded+7
- backend/api/notifications/models.pyAdded+1
- backend/api/notifications/serializers.pyAdded+22
- backend/api/notifications/tests.pyAdded+3
- backend/api/notifications/urls.pyAdded+6
- backend/api/notifications/views.pyAdded+3
- backend/requirements.txtAdded+14
- docker-compose.ymlAdded+28
- frontend/DockerfileAdded+12
- frontend/package-lock.jsonAdded
- frontend/package.jsonAdded+32
- frontend/public/favicon.icoAdded
- frontend/public/index.htmlAdded+43
- frontend/public/manifest.jsonAdded+25
- frontend/public/robots.txtAdded+3
- frontend/src/App.cssAdded
- frontend/src/App.jsAdded+470
- frontend/src/index.cssAdded+6
- frontend/src/index.jsAdded+28
- frontend/src/reportWebVitals.jsAdded+13
- frontend/src/setupTests.jsAdded+5
- frontend/src/store/index.jsAdded+35
- frontend/src/theme.jsAdded+63
- ml/data/README.mdAdded+22
- ml/models/__init__.pyAdded
- ml/models/cnn_pytorch.pyAdded+42
- ml/models/cnn_tensorflow.pyAdded+32
- ml/models/train.pyAdded+154
- ml/requirements.txtAdded+13
- ml/utils/__init__.pyAdded
- ml/utils/prep.pyAdded+174
12345678910111213141516171819202122232425262728293031# Nodenode_modules/npm-debug.log*yarn-debug.log*yarn-error.log*
# React buildfrontend/build/
# Python__pycache__/*.pyc*.pyo*.pyd.Python
# Virtual envvenv/env/.env
# Djangodb.sqlite3
# OS.DS_StoreThumbs.db
# IDE.vscode/.idea/1235 unmodified lines91011---title: Intel Classificationemoji: 🌖5 unmodified lines---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345 unmodified lines101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295<<<<<<< HEAD---title: Intel Classificationemoji: 🌖5 unmodified lines---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference=======# Intel Image ClassifierApplication web full-stack pour la classification de scènes naturelles (Intel Image Classification dataset) avec deux modèles CNN — PyTorch et TensorFlow.---## Structure du projet```intel-classifier/├── backend/ # API Django REST│ ├── api/│ │ ├── api/│ │ │ ├── settings.py│ │ │ ├── urls.py│ │ │ ├── wsgi.py│ │ │ └── asgi.py│ │ ├── notifications/│ │ │ ├── api_views.py # Endpoint de classification│ │ │ ├── serializers.py│ │ │ └── urls.py│ │ ├── models/│ │ │ ├── danielle_model.pth ← À placer ici (PyTorch)│ │ │ └── danielle_model.keras ← À placer ici (TensorFlow)│ │ └── manage.py│ ├── requirements.txt│ └── Dockerfile│├── frontend/ # Interface React + MUI│ ├── src/│ │ ├── App.js # Composant principal│ │ ├── theme.js│ │ └── store/index.js│ ├── public/│ ├── package.json│ └── Dockerfile│├── ml/ # Code d'entraînement│ ├── models/│ │ ├── cnn_pytorch.py # Architecture CNN PyTorch│ │ ├── cnn_tensorflow.py # Architecture CNN TensorFlow│ │ └── train.py # Trainer class│ ├── utils/│ │ └── prep.py # Data loaders + CLASSES│ ├── train_kaggle.py # Script d'entraînement Kaggle│ └── data/│ ├── seg_train/ ← Dataset train à placer ici│ └── seg_test/ ← Dataset test à placer ici│└── docker-compose.yml```---## Classes| Classe | FR | Wolof ||------------|-------------|---------------|| buildings | Bâtiments | Kër yi || forest | Forêt | Géej bu wees || glacier | Glacier | Dëkk bu sedd || mountain | Montagne | Tund bi || sea | Mer | Géej bi || street | Rue | Yoon bi |---## Prérequis- Python 3.10+- Node.js 18+- pip- npm- (Optionnel) Docker + Docker Compose---## Installation et lancement (sans Docker)### 1. Placer les modèles entraînésCopie tes fichiers modèles dans le dossier backend :```backend/api/models/danielle_model.pth ← modèle PyTorchbackend/api/models/danielle_model.keras ← modèle TensorFlow```> Si tu n'as qu'un seul modèle, l'autre sera simplement indisponible à la sélection.---### 2. Backend (Django)```bash# Aller dans le dossier backendcd backend# Créer un environnement virtuelpython -m venv venv# Activer l'environnement virtuel# Windows :venv\Scripts\activate# Mac/Linux :source venv/bin/activate# Installer les dépendancespip install -r requirements.txt# Aller dans le dossier Djangocd api# Appliquer les migrationspython manage.py migrate# Lancer le serveurpython manage.py runserver```Le backend sera disponible sur : **http://127.0.0.1:8000**API Swagger disponible sur : **http://127.0.0.1:8000/swagger/**---### 3. Frontend (React)Ouvre un **nouveau terminal** :```bash# Aller dans le dossier frontendcd frontend# Installer les dépendancesnpm install# Lancer l'applicationnpm start```Le frontend sera disponible sur : **http://localhost:3000**---## Installation et lancement (avec Docker)```bash# À la racine du projetdocker-compose up --build```- Frontend : http://localhost:3000- Backend : http://localhost:8000- Swagger : http://localhost:8000/swagger/---## Entraînement des modèles### Sur Kaggle (recommandé)1. Upload `ml/train_kaggle.py` dans un notebook Kaggle2. Active le GPU (Settings → Accelerator → GPU T4)3. Ajoute le dataset `puneet6060/intel-image-classification`4. Exécute le notebook5. Télécharge `danielle_model.pth` et `danielle_model.keras`6. Place-les dans `backend/api/models/`### En local```bashcd ml# Installer les dépendances MLpip install torch torchvision tensorflow numpy matplotlib seaborn scikit-learn tqdm pillow# Entraîner le modèle PyTorchpython -m models.train --model pytorch --epochs 25 --data data# Entraîner le modèle TensorFlowpython -m models.train --model tensorflow --epochs 25 --data data```Structure du dataset attendue :```ml/data/├── seg_train/│ └── seg_train/│ ├── buildings/│ ├── forest/│ ├── glacier/│ ├── mountain/│ ├── sea/│ └── street/└── seg_test/└── seg_test/├── buildings/├── forest/...```---## API — Endpoint de classification### `POST /api/classify/`**Paramètres (form-data) :**| Paramètre | Type | Requis | Description ||------------|--------|--------|------------------------------------|| image | file | Non* | Fichier image (jpg, png...) || image_url | string | Non* | URL d'une image en ligne || model | string | Non | `pytorch` (défaut) ou `tensorflow` |*Au moins `image` ou `image_url` est requis.**Réponse (200 OK) :**```json{"predicted_class": "forest","confidence": 0.97,"model_used": "pytorch","all_probabilities": [{ "class": "forest", "probability": 0.97 },{ "class": "mountain", "probability": 0.01 },{ "class": "glacier", "probability": 0.01 },{ "class": "sea", "probability": 0.01 },{ "class": "buildings", "probability": 0.00 },{ "class": "street", "probability": 0.00 }]}```---## Fonctionnalités de l'interface- Upload d'image depuis le disque- Chargement d'image depuis une URL- Sélection du modèle (PyTorch CNN / TensorFlow CNN)- Affichage du résultat avec barre de confiance- Affichage de toutes les probabilités par classe- Interface multilingue : **Anglais / Français / Wolof**- Design responsive avec Material UI---## Technologies utilisées| Couche | Technologies ||------------|-------------------------------------------------|| Frontend | React 19, Material UI 6, Axios || Backend | Django 5, Django REST Framework, drf-yasg || ML | PyTorch 2.2, TensorFlow 2.16, torchvision, timm || Données | Intel Image Classification (Kaggle) || DevOps | Docker, Docker Compose |---## Problèmes fréquents**Erreur CORS au démarrage du frontend**→ Vérifie que le backend tourne sur `http://127.0.0.1:8000`**`Model file not found`**→ Vérifie que `danielle_model.pth` et/ou `danielle_model.keras` sont bien dans `backend/api/models/`**`ModuleNotFoundError: No module named 'notifications'`**→ Lance `manage.py` depuis le dossier `backend/api/` et non depuis `backend/`**TensorFlow lent au premier chargement**→ Normal, le modèle est chargé en mémoire à la première requête (lazy loading)---## AuteursProjet universitaire — Classification d'images Intel — 2026>>>>>>> b102039 (Initial commit - Intel Image Classifier)
123DEBUG=TrueSECRET_KEY=change-this-in-productionALLOWED_HOSTS=*123456789101112FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "api/manage.py", "runserver", "0.0.0.0:8000"]12345678910111213141516"""ASGI config for api project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, seehttps://docs.djangoproject.com/en/5.1/howto/deployment/asgi/"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings')
application = get_asgi_application()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112import osfrom pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'django-insecure-intel-image-classifier-change-in-production'
DEBUG = True
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'django_filters', 'drf_yasg', 'notifications',]
MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',]
ROOT_URLCONF = 'api.urls'
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]
WSGI_APPLICATION = 'api.wsgi.application'ASGI_APPLICATION = 'api.asgi.application'
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }}
REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, 'DEFAULT_PERMISSION_CLASSES': [], 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],}
USE_X_FORWARDED_HOST = TrueSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
CORS_ALLOW_ALL_ORIGINS = True
CSRF_TRUSTED_ORIGINS = [ 'http://localhost:3000', 'http://127.0.0.1:3000', 'http://localhost', 'http://127.0.0.1',]
LANGUAGE_CODE = 'en-us'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_TZ = True
STATIC_URL = 'static/intel-classifier/'STATIC_ROOT = os.path.join(BASE_DIR, 'static')MEDIA_ROOT = os.path.join(BASE_DIR, 'media')MEDIA_URL = '/media/intel-classifier/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': {'level': 'DEBUG', 'class': 'logging.StreamHandler'}, 'file': {'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': 'app.log'}, }, 'loggers': {},}123456789101112131415161718192021222324252627282930from django.contrib import adminfrom django.urls import path, include, re_pathfrom django.conf.urls.static import staticfrom django.conf import settingsfrom rest_framework import permissionsfrom drf_yasg.views import get_schema_viewfrom drf_yasg import openapi
schema_view = get_schema_view( openapi.Info( title="Intel Image Classifier API", default_version='v1', description="API for classifying natural scene images (buildings, forest, glacier, mountain, sea, street)", contact=openapi.Contact(email="contact@example.com"), license=openapi.License(name="MIT"), ), public=True, permission_classes=(permissions.AllowAny,),)
urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('notifications.urls')), re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)12345678910111213141516"""WSGI config for api project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, seehttps://docs.djangoproject.com/en/5.1/howto/deployment/wsgi/"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings')
application = get_wsgi_application()12345678910111213141516171819202122#!/usr/bin/env python"""Django's command-line utility for administrative tasks."""import osimport sys
def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.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()1234567# Models
Place your trained model files here:
- `pytorch_model.pth` — PyTorch CNN model- `tensorflow_model.keras` — TensorFlow CNN model
123version https://git-lfs.github.com/spec/v1oid sha256:13d195dc6d7c62d86cc3a039a39f7eef1a119f6e67c1960fd161219635ac31c2size 4859453123from django.contrib import admin# Register your models here.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218import sysfrom pathlib import Pathimport numpy as npimport requestsfrom io import BytesIO
from PIL import Image
from rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework import status
from notifications.serializers import ImageClassifierSerializer, ClassificationResultSerializer
import torchimport torch.nn as nnfrom torchvision import transforms
import tensorflow as tf
# PATHS
BASE_DIR = Path(__file__).resolve().parent.parentPYTORCH_PATH = BASE_DIR / "models" / "pytorch_model.pth"TENSORFLOW_PATH = BASE_DIR / "models" / "model_best.keras"
CLASSES = ["buildings", "forest", "glacier", "mountain", "sea", "street"]
CONFIDENCE_THRESHOLD = 0.6
# PYTORCH MODEL
class CNN(nn.Module): def __init__(self, num_classes=6): super().__init__()
self.block1 = self._block(3, 32) self.block2 = self._block(32, 64) self.block3 = self._block(64, 128) self.block4 = self._block(128, 256)
self.gap = nn.AdaptiveAvgPool2d(1) self.fc1 = nn.Linear(256, 128) self.fc2 = nn.Linear(128, num_classes) self.dropout = nn.Dropout(0.5)
def _block(self, in_c, out_c): return nn.Sequential( nn.Conv2d(in_c, out_c, 3, padding=1), nn.BatchNorm2d(out_c), nn.ReLU(), nn.Conv2d(out_c, out_c, 3, padding=1), nn.BatchNorm2d(out_c), nn.ReLU(), nn.MaxPool2d(2) )
def forward(self, x): x = self.block1(x) x = self.block2(x) x = self.block3(x) x = self.block4(x)
x = self.gap(x) x = x.view(x.size(0), -1)
x = self.dropout(torch.relu(self.fc1(x))) x = self.fc2(x) return x
# TRANSFORM
pytorch_transform = transforms.Compose([ transforms.Resize((150, 150)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
_pytorch_model = None_tensorflow_model = None
def get_pytorch_model(): global _pytorch_model if _pytorch_model is None: model = CNN(num_classes=len(CLASSES)) model.load_state_dict(torch.load(str(PYTORCH_PATH), map_location="cpu")) model.eval() _pytorch_model = model return _pytorch_model
def get_tensorflow_model(): global _tensorflow_model if _tensorflow_model is None: _tensorflow_model = tf.keras.models.load_model(str(TENSORFLOW_PATH), compile=False) return _tensorflow_model
class ImageClassifierAPIView(APIView):
def post(self, request): serializer = ImageClassifierSerializer(data=request.data)
if not serializer.is_valid(): return Response(serializer.errors, status=400)
try: if "image" in serializer.validated_data: image = Image.open(serializer.validated_data["image"]).convert("RGB")
else: image_url = serializer.validated_data["image_url"]
if not image_url.startswith("http"): return Response({"error": "Invalid URL"}, status=400)
resp = requests.get(image_url, timeout=10) resp.raise_for_status()
image = Image.open(BytesIO(resp.content)).convert("RGB")
model_name = serializer.validated_data.get("model", "pytorch")
if model_name == "pytorch": result = self._predict_pytorch(image) else: result = self._predict_tensorflow(image)
result["model_used"] = model_name
return Response(result, status=200)
except Exception as e: print("ERROR:", e) return Response({"error": str(e)}, status=400)
def _predict_pytorch(self, image): model = get_pytorch_model() tensor = pytorch_transform(image).unsqueeze(0)
with torch.no_grad(): outputs = model(tensor) probs = torch.nn.functional.softmax(outputs, dim=1)
values, indices = torch.topk(probs, k=len(CLASSES), dim=1)
values = values.squeeze().cpu().numpy() indices = indices.squeeze().cpu().numpy()
confidence = float(values[0])
all_probs = [ {"class": CLASSES[indices[i]], "probability": float(values[i])} for i in range(len(CLASSES)) ]
if confidence < CONFIDENCE_THRESHOLD: return { "predicted_class": "unknown", "confidence": confidence, "all_probabilities": all_probs }
return { "predicted_class": CLASSES[indices[0]], "confidence": confidence, "all_probabilities": all_probs }
# TENSORFLOW
def _predict_tensorflow(self, image):
model = get_tensorflow_model()
img = image.resize((130, 130)) arr = np.array(img, dtype=np.float32) arr = arr[:, :, ::-1] arr = np.expand_dims(arr, 0)
preds = model.predict(arr, verbose=0)[0] sorted_idx = np.argsort(preds)[::-1]
confidence = float(preds[sorted_idx[0]])
all_probs = [ {"class": CLASSES[i], "probability": float(preds[i])} for i in sorted_idx ]
if confidence < CONFIDENCE_THRESHOLD:
return { "predicted_class": "unknown", "confidence": confidence, "all_probabilities": all_probs }
return { "predicted_class": CLASSES[sorted_idx[0]], "confidence": confidence, "all_probabilities": all_probs }1234567from django.apps import AppConfig
class NotificationsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'notifications'
1from django.db import models12345678910111213141516171819202122from rest_framework import serializers
class ImageClassifierSerializer(serializers.Serializer): image = serializers.ImageField(required=False) image_url = serializers.URLField(required=False) model = serializers.ChoiceField( choices=['pytorch', 'tensorflow'], default='pytorch' )
def validate(self, data): if not data.get('image') and not data.get('image_url'): raise serializers.ValidationError("Provide either 'image' or 'image_url'.") return data
class ClassificationResultSerializer(serializers.Serializer): predicted_class = serializers.CharField() model_used = serializers.CharField() confidence = serializers.FloatField() all_probabilities = serializers.ListField(child=serializers.DictField())123from django.test import TestCase
# Create your tests here.123456from django.urls import pathfrom notifications.api_views import ImageClassifierAPIView
urlpatterns = [ path('classify/', ImageClassifierAPIView.as_view(), name='api_classify'),]123from django.shortcuts import render
# Create your views here.1234567891011121314Django>=5.0djangorestframework>=3.14.0django-environdjango-filterdjango-cors-headerspython-dotenvPillowrequestsdrf_yasgtorch>=2.2.0torchvision>=0.17.0tensorflow>=2.16.0numpy>=1.26.0timm12345678910111213141516171819202122232425262728version: "3.9"
services:
backend: build: context: ./backend dockerfile: Dockerfile ports: - "8000:8000" volumes: - ./backend:/app - ./ml/models:/app/api/models # mount trained models environment: - DEBUG=True restart: unless-stopped
frontend: build: context: ./frontend dockerfile: Dockerfile ports: - "3000:3000" depends_on: - backend environment: - REACT_APP_API_URL=http://localhost:8000 restart: unless-stopped123456789101112FROM node:20-alpine
WORKDIR /app
COPY package.json .RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]1234567891011121314151617181920212223242526272829303132{ "proxy": "http://127.0.0.1:5000", "name": "intel-image-classifier", "version": "1.0.0", "private": true, "dependencies": { "@emotion/react": "^11.14.0", "@emotion/styled": "^11.14.0", "@mui/icons-material": "^6.4.0", "@mui/material": "^6.4.0", "@reduxjs/toolkit": "^2.5.0", "axios": "^1.15.0", "react": "^19.0.0", "react-dom": "^19.0.0", "react-redux": "^9.2.0", "react-router-dom": "^7.1.1", "react-scripts": "^5.0.1" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": ["react-app", "react-app/jest"] }, "browserslist": { "production": [">0.2%", "not dead", "not op_mini all"], "development": ["last 1 chrome version", "last 1 firefox version", "last 1 safari version"] }}12345678910111213141516171819202122232425262728293031323334353637383940414243<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <!-- manifest.json provides metadata used when your web app is installed on a user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <!-- Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> <title>DANIELLE</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <!-- This HTML file is a template. If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file. The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. --> </body></html>12345678910111213141516171819202122232425{ "short_name": "React App", "name": "Create React App Sample", "icons": [ { "src": "favicon.ico", "sizes": "64x64 32x32 24x24 16x16", "type": "image/x-icon" }, { "src": "logo192.png", "type": "image/png", "sizes": "192x192" }, { "src": "logo512.png", "type": "image/png", "sizes": "512x512" } ], "start_url": ".", "display": "standalone", "theme_color": "#000000", "background_color": "#ffffff"}123# https://www.robotstxt.org/robotstxt.htmlUser-agent: *Disallow:123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470import React, { useState, useMemo } from "react";import axios from "axios";
import { Box, Button, Container, Typography, Paper, ThemeProvider, createTheme, IconButton, Card, CardMedia, Chip, AppBar, Toolbar, TextField, Select, FormControl, InputLabel, MenuItem, LinearProgress, Collapse, Tooltip, Divider} from "@mui/material";
import { CloudUpload as CloudUploadIcon, Landscape as LandscapeIcon, DarkMode as DarkModeIcon, LightMode as LightModeIcon, ExpandMore as ExpandMoreIcon, ExpandLess as ExpandLessIcon, GitHub as GitHubIcon, LinkedIn as LinkedInIcon} from "@mui/icons-material";
const LANGUAGES = [ { code: "en", flag: "en", label: "English" }, { code: "fr", flag: "fr", label: "Français" }, { code: "wo", flag: "wo", label: "Wolof" },];
function App() {
const [mode, setMode] = useState("light");
const theme = useMemo(() => createTheme({ palette: { mode, primary: { main: "#2e7d32" }, }, shape: { borderRadius: 16 }, components: { MuiPaper: { styleOverrides: { root: { borderRadius: 20, boxShadow: mode === "dark" ? "0 8px 32px rgba(0,0,0,0.6)" : "0 8px 32px rgba(0,0,0,0.12)", transition: "transform 0.25s ease, box-shadow 0.25s ease", "&:hover": { transform: "translateY(-4px)", boxShadow: mode === "dark" ? "0 16px 48px rgba(0,0,0,0.7)" : "0 16px 48px rgba(0,0,0,0.18)", }, }, }, }, MuiCard: { styleOverrides: { root: { borderRadius: 20, boxShadow: mode === "dark" ? "0 8px 32px rgba(0,0,0,0.6)" : "0 8px 32px rgba(0,0,0,0.12)", transition: "transform 0.25s ease, box-shadow 0.25s ease", "&:hover": { transform: "translateY(-4px)", boxShadow: mode === "dark" ? "0 16px 48px rgba(0,0,0,0.7)" : "0 16px 48px rgba(0,0,0,0.18)", }, }, }, }, MuiButton: { styleOverrides: { root: { borderRadius: 10, textTransform: "none", fontWeight: 600 }, }, }, }, }), [mode] );
const [language, setLanguage] = useState("en");
const texts = { en: { title: "Intel Image Classifier", subtitle: "Classify natural scenes", upload: "Upload Image", urlBtn: "Load image from URL", classify: "Classify", result: "Result", confidence: "Confidence", selectModel: "Select Model", processing: "Processing...", selectImage: "Please provide an image", classes: "Possible Classes", reset: "Reset", details: "Details", hideDetails: "Hide", unknown: "Image not recognized", }, fr: { title: "Classificateur Intel", subtitle: "Classifiez des scènes naturelles avec le deep learning", upload: "Télécharger Image", urlBtn: "Charger image depuis URL", classify: "Classer", result: "Résultat", confidence: "Confiance", selectModel: "Choisir modèle", processing: "Traitement...", selectImage: "Veuillez fournir une image", classes: "Classes possibles", reset: "Réinitialiser", details: "Détails", hideDetails: "Masquer", unknown: "Image non reconnue", }, wo: { title: "Intel Xët-Nataal (IA)", subtitle: "Jëfandikoo IA ngir xool nataal yi", upload: "Yeb Nataal bi", urlBtn: "Yeb nataal ci URL", classify: "Wone", result: "Njëg", confidence: "Loo xam ne", selectModel: "Tànn modil", processing: "Di liggéey...", selectImage: "Tànnal ab nataal", classes: "Yëgël yi", reset: "Tàkku", details: "Xam ci kanam", hideDetails: "Planque", unknown: "Nataal xamul", } };
const t = texts[language];
const CLASS_LABELS = { buildings: { en: "Buildings", fr: "Bâtiments", wo: "Kër yi" }, forest: { en: "Forest", fr: "Forêt", wo: "Géej bu wees" }, glacier: { en: "Glacier", fr: "Glacier", wo: "Dëkk bu sedd" }, mountain: { en: "Mountain", fr: "Montagne", wo: "Tund bi" }, sea: { en: "Sea", fr: "Mer", wo: "Géej bi" }, street: { en: "Street", fr: "Rue", wo: "Yoon bi" }, };
const getLabel = (cls) => CLASS_LABELS[cls]?.[language] ?? cls;
const [selectedImage, setSelectedImage] = useState(null); const [imageUrl, setImageUrl] = useState(""); const [preview, setPreview] = useState(null); const [showUrlInput, setShowUrlInput] = useState(false); const [model, setModel] = useState("pytorch"); const [result, setResult] = useState(null); const [isProcessing, setIsProcessing] = useState(false); const [error, setError] = useState(null); const [showDetails, setShowDetails] = useState(false);
const handleImageUpload = (event) => { const file = event.target.files[0]; if (!file) return; setSelectedImage(file); setPreview(URL.createObjectURL(file)); setImageUrl(""); setResult(null); setError(null); setShowDetails(false); };
const resetAll = () => { setSelectedImage(null); setImageUrl(""); setPreview(null); setResult(null); setError(null); setShowDetails(false); };
const processImage = async () => { if (!selectedImage && !imageUrl) { setError(t.selectImage); return; } setIsProcessing(true); setError(null);
try { const formData = new FormData(); if (selectedImage) { formData.append("image", selectedImage); } else { formData.append("image_url", imageUrl); } formData.append("model", model);
const response = await axios.post( "http://127.0.0.1:8000/api/classify/", formData, { headers: { "Content-Type": "multipart/form-data" } } );
const data = response.data; const conf = Math.round((parseFloat(data.confidence) || 0) * 100); const allProbs = (data.all_probabilities || []).map(item => ({ class: item.class, probability: parseFloat(item.probability) || 0 }));
setResult({ predictedClass: conf < 50 ? "unknown" : (data.predicted_class || "unknown"), confidence: conf, allProbabilities: allProbs, modelUsed: data.model_used || model });
} catch (err) { console.error(err); setError("Classification error. Please try again."); } finally { setIsProcessing(false); } };
return ( <ThemeProvider theme={theme}> <Box sx={{ minHeight: "100vh", display: "flex", flexDirection: "column", bgcolor: "background.default", color: "text.primary" }}>
{/* HEADER */} <AppBar position="static" color="transparent" elevation={0} sx={{ borderBottom: "1px solid", borderColor: "divider" }}> <Toolbar> <LandscapeIcon sx={{ mr: 2, color: "primary.main" }} /> <Typography variant="h6" sx={{ flexGrow: 1, fontWeight: 800 }}> {t.title} </Typography> <Box sx={{ display: "flex", alignItems: "center", gap: 0.5, mr: 1 }}> {LANGUAGES.map((lang) => ( <Tooltip key={lang.code} title={lang.label}> <IconButton onClick={() => setLanguage(lang.code)} size="small" sx={{ fontSize: "1.4rem", opacity: language === lang.code ? 1 : 0.35, transition: "opacity 0.2s", p: "4px", "&:hover": { opacity: 0.8 } }} > {lang.flag} </IconButton> </Tooltip> ))} </Box> <Tooltip title={mode === "light" ? "Dark mode" : "Light mode"}> <IconButton onClick={() => setMode(mode === "light" ? "dark" : "light")}> {mode === "light" ? <DarkModeIcon /> : <LightModeIcon />} </IconButton> </Tooltip> </Toolbar> </AppBar>
{/* MAIN */} <Container maxWidth="md" sx={{ mt: 4, flex: 1 }}>
{/* INPUT BOX */} <Paper sx={{ p: 4 }} elevation={3}> <Typography variant="h4" align="center" sx={{ fontWeight: 800, mb: 1 }}> {t.title} </Typography> <Typography align="center" color="text.secondary" sx={{ mb: 3 }}> {t.subtitle} </Typography>
<FormControl fullWidth sx={{ mt: 1 }}> <InputLabel>{t.selectModel}</InputLabel> <Select value={model} label={t.selectModel} onChange={(e) => setModel(e.target.value)} > <MenuItem value="pytorch">PyTorch CNN</MenuItem> <MenuItem value="tensorflow">TensorFlow CNN</MenuItem> </Select> </FormControl>
<Box sx={{ mt: 3, display: "flex", gap: 3, flexWrap: "wrap" }}> <Box sx={{ flex: 1, minWidth: "250px" }}> <Typography gutterBottom>{t.upload}</Typography> <Button fullWidth variant="outlined" startIcon={<CloudUploadIcon />} component="label"> {t.upload} <input type="file" hidden accept="image/*" onChange={handleImageUpload} /> </Button> </Box> <Box sx={{ flex: 1, minWidth: "250px" }}> <Typography gutterBottom>{t.urlBtn}</Typography> <Button fullWidth variant="outlined" color="primary" startIcon={<CloudUploadIcon />} onClick={() => setShowUrlInput(!showUrlInput)}> {t.urlBtn} </Button> {showUrlInput && ( <TextField fullWidth label="URL" value={imageUrl} onChange={(e) => { setImageUrl(e.target.value); setSelectedImage(null); setPreview(e.target.value); }} sx={{ mt: 2 }} /> )} </Box> </Box>
<Box sx={{ mt: 3 }}> <Typography variant="subtitle2" color="text.secondary" gutterBottom> {t.classes}: </Typography> <Box sx={{ display: "flex", flexWrap: "wrap", gap: 1 }}> {Object.keys(CLASS_LABELS).map((cls) => ( <Chip key={cls} label={getLabel(cls)} size="small" variant="outlined" /> ))} </Box> </Box> </Paper>
{/* IMAGE PREVIEW */} {preview && ( <Card sx={{ mt: 3, p: 2, textAlign: "center" }}> <CardMedia component="img" height="300" image={preview} sx={{ objectFit: "contain", borderRadius: 2 }} /> {isProcessing && <LinearProgress sx={{ mt: 1 }} color="primary" />} <Box sx={{ mt: 2 }}> <Button variant="contained" color="primary" onClick={processImage} disabled={isProcessing} size="large"> {isProcessing ? t.processing : t.classify} </Button> </Box> </Card> )}
{/* ERROR */} {error && ( <Paper sx={{ mt: 2, p: 2, backgroundColor: "#ffebee" }}> <Typography color="error">{error}</Typography> </Paper> )}
{/* RESULT */} {result && ( <Paper sx={{ mt: 3, p: 3, textAlign: "center" }}> <Typography variant="h6" fontWeight={700} gutterBottom> {t.result} </Typography>
<Chip label={result.predictedClass === "unknown" ? t.unknown : getLabel(result.predictedClass)} color={result.predictedClass === "unknown" ? "error" : "success"} sx={{ fontSize: "1.1rem", px: 2, py: 2.5, mt: 1, fontWeight: 700 }} />
<Typography sx={{ mt: 2 }}> {t.confidence}: <strong>{result.confidence}%</strong> </Typography> <Typography variant="caption" color="text.secondary"> Model: {result.modelUsed} </Typography>
<Collapse in={showDetails}> <Box sx={{ mt: 2, textAlign: "left" }}> {result.allProbabilities.map((item) => ( <Box key={item.class} sx={{ mb: 1.5 }}> <Box sx={{ display: "flex", justifyContent: "space-between", mb: 0.5 }}> <Typography variant="body2" fontWeight={600}> {getLabel(item.class)} </Typography> <Typography variant="body2"> {Math.round(item.probability * 100)}% </Typography> </Box> <LinearProgress variant="determinate" value={Math.round(item.probability * 100)} sx={{ height: 8, borderRadius: 4 }} color="primary" /> </Box> ))} </Box> </Collapse>
<Box sx={{ mt: 3, display: "flex", justifyContent: "center", gap: 2 }}> <Button variant="outlined" onClick={resetAll}>{t.reset}</Button> <Button variant="outlined" color="primary" onClick={() => setShowDetails(!showDetails)} endIcon={showDetails ? <ExpandLessIcon /> : <ExpandMoreIcon />}> {showDetails ? t.hideDetails : t.details} </Button> </Box> </Paper> )}
</Container>
{/* FOOTER */} <Box sx={{ mt: "auto" }}> <Divider /> <Box sx={{ py: 1.5, px: 4, display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 1 }}> <Typography variant="body2" color="text.secondary"> © 2026 Intel Image Classifier By <strong>Tsemo Danielle</strong> </Typography> <Box sx={{ display: "flex", gap: 1 }}> <Tooltip title="GitHub"> <IconButton size="small" onClick={() => window.open("https://github.com/nguemtchuengdanielle/")}> <GitHubIcon fontSize="small" /> </IconButton> </Tooltip> <Tooltip title="LinkedIn"> <IconButton size="small" onClick={() => window.open("https://linkedin.com/in/danielle-tsemo3")} sx={{ color: "#0077b5" }}> <LinkedInIcon fontSize="small" /> </IconButton> </Tooltip> </Box> </Box> </Box>
</Box> </ThemeProvider> );}
export default App;123456@import url('https://fonts.googleapis.com/css2?family=Dancing+Script:wght@400..700&display=swap');@import url('https://fonts.googleapis.com/css2?family=Dancing+Script:wght@400..700&family=Quicksand:wght@300..700&display=swap');*{ margin: 0px; padding: 0px;}12345678910111213141516171819202122232425262728import React from 'react';import ReactDOM from 'react-dom/client';import './index.css';import App from './App';import {BrowserRouter} from "react-router-dom";import axios from 'axios';import {Provider} from 'react-redux'
import { store } from './store';
axios.defaults.baseURL = process.env.REACT_APP_API_URL || "http://localhost:8081";
document.title = "Classification de Prunes";const root = ReactDOM.createRoot(document.getElementById('root'));root.render( <React.StrictMode> <BrowserRouter> <Provider store={store} > <App /> </Provider> </BrowserRouter> </React.StrictMode>);
12345678910111213const reportWebVitals = onPerfEntry => { if (onPerfEntry && onPerfEntry instanceof Function) { import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { getCLS(onPerfEntry); getFID(onPerfEntry); getFCP(onPerfEntry); getLCP(onPerfEntry); getTTFB(onPerfEntry); }); }};
export default reportWebVitals;12345// jest-dom adds custom jest matchers for asserting on DOM nodes.// allows you to do things like:// expect(element).toHaveTextContent(/react/i)// learn more: https://github.com/testing-library/jest-domimport '@testing-library/jest-dom';1234567891011121314151617181920212223242526272829303132333435import {createSlice, configureStore} from '@reduxjs/toolkit';
const authSlice = createSlice({ name: "auth", initialState: { isLoggedIn: false, isAdmin: false, openSnackbar: false, msg: "", snackbarId: 0 , }, reducers: { login(state) { state.isLoggedIn = true; }, setAdmin(state){ state.isAdmin = true; }, logout(state) { state.isLoggedIn = false; state.isAdmin = false; }, resetSnackbar(state) { state.openSnackbar = false; state.msg = ""; } },});
export const authActions = authSlice.actions;
export const store = configureStore({ reducer: authSlice.reducer});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import { createTheme } from '@mui/material';
// Custom theme with fruit-inspired colorsconst theme = createTheme({ palette: { primary: { main: '#4caf50', light: '#80e27e', dark: '#087f23' }, secondary: { main: '#ff9800', dark: '#c66900' }, error: { main: '#f44336', light: '#ff7961', dark: '#ba000d' }, background: { default: '#f5f5f5', paper: '#ffffff' } }, typography: { fontFamily: '"Poppins", "Roboto", "Helvetica", "Arial", sans-serif', h4: { fontWeight: 600 } }, shape: { borderRadius: 12 }, components: { MuiButton: { styleOverrides: { root: { borderRadius: 30, textTransform: 'none', fontWeight: 600, padding: '10px 20px' } } }, MuiPaper: { styleOverrides: { root: { boxShadow: '0 8px 24px rgba(0, 0, 0, 0.12)' } } }, MuiChip: { styleOverrides: { root: { fontWeight: 600, fontSize: '0.9rem' } } } }});
export default theme;12345678910111213141516171819202122# Dataset
Download the Intel Image Classification dataset from Kaggle:https://www.kaggle.com/datasets/puneet6060/intel-image-classification
Extract and place in this structure:
```ml/data/├── seg_train/│ └── seg_train/│ ├── buildings/│ ├── forest/│ ├── glacier/│ ├── mountain/│ ├── sea/│ └── street/└── seg_test/ └── seg_test/ ├── buildings/ ...```123456789101112131415161718192021222324252627282930313233343536373839404142import torch.nn as nn
class CNN(nn.Module): def __init__(self, num_classes=6): super(CNN, self).__init__()
self.block1 = self._block(3, 32) self.block2 = self._block(32, 64) self.block3 = self._block(64, 128) self.block4 = self._block(128, 256)
self.gap = nn.AdaptiveAvgPool2d(1)
self.fc1 = nn.Linear(256, 128) self.fc2 = nn.Linear(128, num_classes)
self.relu = nn.ReLU() self.dropout = nn.Dropout(0.5)
def _block(self, in_c, out_c): return nn.Sequential( nn.Conv2d(in_c, out_c, kernel_size=3, padding=1), nn.BatchNorm2d(out_c), nn.ReLU(), nn.MaxPool2d(2) )
def forward(self, x): x = self.block1(x) x = self.block2(x) x = self.block3(x) x = self.block4(x)
x = self.gap(x) x = x.view(x.size(0), -1)
x = self.dropout(x) x = self.relu(self.fc1(x)) x = self.dropout(x) x = self.fc2(x)
return x1234567891011121314151617181920212223242526272829303132import tensorflow as tffrom tensorflow.keras import layers, models
def build_model(num_classes=6, input_shape=(150, 150, 3)): inputs = layers.Input(shape=input_shape)
def block(x, filters): x = layers.Conv2D(filters, 3, padding="same", activation=None)(x) x = layers.BatchNormalization()(x) x = layers.ReLU()(x) x = layers.MaxPooling2D()(x) return x
x = block(inputs, 32) x = block(x, 64) x = block(x, 128) x = block(x, 256)
x = layers.GlobalAveragePooling2D()(x) x = layers.Dropout(0.5)(x)
outputs = layers.Dense(num_classes)(x)
model = models.Model(inputs, outputs)
model.compile( optimizer="adam", loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"] )
return model123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154import argparseimport torchimport tensorflow as tf
from torch.utils.data import DataLoader, random_splitfrom torchvision import datasets, transforms
from models.cnn_pytorch import CNNfrom models.cnn_tensorflow import build_modelfrom utils.prep import CLASSES
def get_data_loaders(data_path, batch_size=32):
transform = transforms.Compose([ transforms.Resize((150, 150)), transforms.ToTensor() ])
train_data = datasets.ImageFolder( f"{data_path}/seg_train/seg_train", transform=transform )
test_data = datasets.ImageFolder( f"{data_path}/seg_test/seg_test", transform=transform )
val_size = int(0.2 * len(train_data)) train_size = len(train_data) - val_size
train_data, val_data = random_split(train_data, [train_size, val_size])
train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True) val_loader = DataLoader(val_data, batch_size=batch_size, shuffle=False) test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=False)
return train_loader, val_loader, test_loader
def train_pytorch(model, train_loader, val_loader, epochs, device):
model.to(device) optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=1e-4) criterion = torch.nn.CrossEntropyLoss()
best_loss = float("inf")
for epoch in range(epochs):
# TRAIN model.train() total_loss, correct, total = 0, 0, 0
for x, y in train_loader: x, y = x.to(device), y.to(device)
optimizer.zero_grad() outputs = model(x) loss = criterion(outputs, y) loss.backward() optimizer.step()
total_loss += loss.item() * y.size(0)
preds = outputs.argmax(1) correct += (preds == y).sum().item() total += y.size(0)
train_acc = 100 * correct / total train_loss = total_loss / total
# VALIDATION model.eval() val_loss, val_correct, val_total = 0, 0, 0
with torch.no_grad(): for x, y in val_loader: x, y = x.to(device), y.to(device) outputs = model(x) loss = criterion(outputs, y)
val_loss += loss.item() * y.size(0)
preds = outputs.argmax(1) val_correct += (preds == y).sum().item() val_total += y.size(0)
val_acc = 100 * val_correct / val_total val_loss = val_loss / val_total
print(f"Epoch {epoch+1}/{epochs} | " f"Train Loss {train_loss:.4f} Acc {train_acc:.2f}% | " f"Val Loss {val_loss:.4f} Acc {val_acc:.2f}%")
# save best model if val_loss < best_loss: best_loss = val_loss torch.save(model.state_dict(), "pytorch_model.pth")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--model", required=True, choices=["pytorch", "tensorflow"]) parser.add_argument("--epochs", type=int, default=25) parser.add_argument("--data", type=str, required=True)
args = parser.parse_args()
device = "cuda" if torch.cuda.is_available() else "cpu"
# PYTORCH if args.model == "pytorch":
train_loader, val_loader, test_loader = get_data_loaders(args.data)
model = CNN(num_classes=len(CLASSES))
train_pytorch(model, train_loader, val_loader, args.epochs, device)
# TENSORFLOW else:
train_ds = tf.keras.preprocessing.image_dataset_from_directory( f"{args.data}/seg_train/seg_train", image_size=(150, 150), batch_size=32 )
val_ds = tf.keras.preprocessing.image_dataset_from_directory( f"{args.data}/seg_test/seg_test", image_size=(150, 150), batch_size=32 )
model = build_model(num_classes=len(CLASSES))
model.fit( train_ds, validation_data=val_ds, epochs=args.epochs )
model.save("tensorflow_model.keras")
if __name__ == "__main__": main()12345678910111213torchtorchvisiontensorflownumpymatplotlibseabornscikit-learntqdmpillow
#cd ml#pip install -r requirements.txt#python -m models.train --model pytorch --epochs 25 --data data123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174import torchimport tensorflow as tffrom torchvision import datasets, transformsfrom torch.utils.data import DataLoaderfrom pathlib import Path
CLASSES = ["buildings", "forest", "glacier", "mountain", "sea", "street"]IMAGE_SIZE = (150, 150)
# PYTORCH DATA LOADER
def get_pytorch_data(data_dir="data", batch_size=64):
data_dir = Path(data_dir)
train_path = data_dir / "seg_train" test_path = data_dir / "seg_test"
train_transform = transforms.Compose([ transforms.Resize(IMAGE_SIZE), transforms.RandomHorizontalFlip(), transforms.RandomVerticalFlip(p=0.1), transforms.RandomRotation(15), transforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.2), transforms.ToTensor(), transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) ])
test_transform = transforms.Compose([ transforms.Resize(IMAGE_SIZE), transforms.ToTensor(), transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) ])
full_train = datasets.ImageFolder( str(train_path), transform=train_transform )
test_dataset = datasets.ImageFolder( str(test_path), transform=test_transform )
print("Class mapping:", full_train.class_to_idx)
# Split train / validation val_size = int(0.2 * len(full_train)) train_size = len(full_train) - val_size
train_dataset, val_dataset = torch.utils.data.random_split( full_train, [train_size, val_size], generator=torch.Generator().manual_seed(42) )
train_loader = DataLoader( train_dataset, batch_size=batch_size, shuffle=True, num_workers=2 )
val_loader = DataLoader( val_dataset, batch_size=batch_size, shuffle=False, num_workers=2 )
test_loader = DataLoader( test_dataset, batch_size=batch_size, shuffle=False, num_workers=2 )
return train_loader, val_loader, test_loader
# TENSORFLOW DATA PIPELINE
def get_tensorflow_data(data_dir="data", batch_size=64):
data_dir = Path(data_dir)
train_dir = data_dir / "seg_train" test_dir = data_dir / "seg_test"
train_ds = tf.keras.utils.image_dataset_from_directory( str(train_dir), image_size=IMAGE_SIZE, batch_size=batch_size, shuffle=True, seed=42, validation_split=0.2, subset="training", label_mode="int", class_names=CLASSES )
val_ds = tf.keras.utils.image_dataset_from_directory( str(train_dir), image_size=IMAGE_SIZE, batch_size=batch_size, shuffle=True, seed=42, validation_split=0.2, subset="validation", label_mode="int", class_names=CLASSES )
test_ds = tf.keras.utils.image_dataset_from_directory( str(test_dir), image_size=IMAGE_SIZE, batch_size=batch_size, shuffle=False, label_mode="int", class_names=CLASSES )
# AUGMENTATION augmentation = tf.keras.Sequential([ tf.keras.layers.RandomFlip("horizontal"), tf.keras.layers.RandomRotation(0.1), tf.keras.layers.RandomZoom(0.1), tf.keras.layers.RandomContrast(0.2), ])
normalization = tf.keras.layers.Rescaling(1.0 / 255)
train_ds = ( train_ds .map(lambda x, y: (augmentation(x, training=True), y), num_parallel_calls=tf.data.AUTOTUNE) .map(lambda x, y: (normalization(x), y), num_parallel_calls=tf.data.AUTOTUNE) .cache() .shuffle(1000) .prefetch(tf.data.AUTOTUNE) )
val_ds = ( val_ds .map(lambda x, y: (normalization(x), y), num_parallel_calls=tf.data.AUTOTUNE) .cache() .prefetch(tf.data.AUTOTUNE) )
test_ds = ( test_ds .map(lambda x, y: (normalization(x), y), num_parallel_calls=tf.data.AUTOTUNE) .cache() .prefetch(tf.data.AUTOTUNE) )
return train_ds, val_ds, test_ds.gitignoreAdded+31
README.md+284
backend/.env.exampleAdded+3
backend/DockerfileAdded+12
backend/api/api/__init__.pyAdded
backend/api/api/asgi.pyAdded+16
backend/api/api/settings.pyAdded+112
backend/api/api/urls.pyAdded+30
backend/api/api/wsgi.pyAdded+16
backend/api/app.logAdded
backend/api/manage.pyAdded+22
backend/api/models/README.mdAdded+7
backend/api/models/pytorch_model.pthAdded+3
backend/api/notifications/__init__.pyAdded
backend/api/notifications/admin.pyAdded+3
backend/api/notifications/api_views.pyAdded+218
backend/api/notifications/apps.pyAdded+7
backend/api/notifications/models.pyAdded+1
backend/api/notifications/serializers.pyAdded+22
backend/api/notifications/tests.pyAdded+3
backend/api/notifications/urls.pyAdded+6
backend/api/notifications/views.pyAdded+3
backend/requirements.txtAdded+14
docker-compose.ymlAdded+28
frontend/DockerfileAdded+12
frontend/package-lock.jsonAdded
frontend/package.jsonAdded+32
frontend/public/favicon.icoAdded
frontend/public/index.htmlAdded+43
frontend/public/manifest.jsonAdded+25
frontend/public/robots.txtAdded+3
frontend/src/App.cssAdded
frontend/src/App.jsAdded+470
frontend/src/index.cssAdded+6
frontend/src/index.jsAdded+28
frontend/src/reportWebVitals.jsAdded+13
frontend/src/setupTests.jsAdded+5
frontend/src/store/index.jsAdded+35
frontend/src/theme.jsAdded+63
ml/data/README.mdAdded+22
ml/models/__init__.pyAdded
ml/models/cnn_pytorch.pyAdded+42
ml/models/cnn_tensorflow.pyAdded+32
ml/models/train.pyAdded+154
ml/requirements.txtAdded+13
ml/utils/__init__.pyAdded
ml/utils/prep.pyAdded+174