Spaces:
Configuration error
Configuration error
Commit ·
01ba07a
0
Parent(s):
Initial clean Space deployment
Browse filesFiles changed (6)
- .gitignoreAdded+6
- DockerfileAdded+11
- README.mdAdded+37
- app.pyAdded+189
- index.htmlAdded+115
- requirements.txtAdded+9
123456__pycache__/*.pyc*.pyo*.pyd.ipynb_checkpoints/.netrc1234567891011FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt ./RUN pip install --no-cache-dir -r requirements.txt
COPY . ./
EXPOSE 7860CMD ["python", "app.py"]12345678910111213141516171819202122232425262728293031323334353637# Minimal Hugging Face Space for Intel Image Classifier
This folder contains a minimal Hugging Face Space app using a custom `index.html` frontend and a Python backend.
## Files- `app.py` — FastAPI backend for prediction and frontend delivery- `index.html` — frontend UI for uploading images and selecting the model- `requirements.txt` — dependencies- `models/` — place your trained models here
## Model files requiredPlace your trained models in `hf_space/models/`:
- `pytorch_model.pth`- `model_best.keras`
## Deploying on Hugging Face Spaces1. Create a new Space on Hugging Face2. Select `Python` SDK3. Push the contents of this `hf_space/` directory to the new Space repository
The Space will run `app.py` automatically and serve `index.html` as the frontend.
## Docker supportA `Dockerfile` is included so you can also build and run the app locally in a container.
## Local testingFrom `hf_space/`:
```bashpip install -r requirements.txtpython app.py```
Then open:
- `http://localhost:7860`123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189import ioimport osfrom pathlib import Pathfrom typing import List
import numpy as npimport torchimport torch.nn as nnfrom torchvision import transformsfrom PIL import Imagefrom fastapi import FastAPI, File, Form, HTTPException, UploadFilefrom fastapi.responses import FileResponse, JSONResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom huggingface_hub import hf_hub_downloadimport uvicorn
BASE_DIR = Path(__file__).resolve().parentMODEL_DIR = BASE_DIR / "models"PYTORCH_PATH = MODEL_DIR / "pytorch_model.pth"TENSORFLOW_PATH = MODEL_DIR / "model_best.keras"MODEL_REPO = "danielle2035/intel-classifier-models"HF_TOKEN = os.environ.get("HF_TOKEN")
CLASSES = ["buildings", "forest", "glacier", "mountain", "sea", "street"]CONFIDENCE_THRESHOLD = 0.6
app = FastAPI(title="Intel Image Classifier")app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
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_channels, out_channels): return nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(), nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1), nn.BatchNorm2d(out_channels), 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
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 download_model_file(filename: str, local_path: Path): if local_path.exists(): return MODEL_DIR.mkdir(parents=True, exist_ok=True) try: hf_hub_download( repo_id=MODEL_REPO, filename=filename, repo_type="model", local_dir=str(MODEL_DIR), local_dir_use_symlinks=False, use_auth_token=HF_TOKEN, ) except Exception as exc: raise FileNotFoundError( f"Unable to download {filename} from {MODEL_REPO}: {exc}" ) from exc
def get_pytorch_model(): global _pytorch_model if _pytorch_model is None: if not PYTORCH_PATH.exists(): download_model_file("models/pytorch_model.pth", PYTORCH_PATH) 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: if not TENSORFLOW_PATH.exists(): download_model_file("models/model_best.keras", TENSORFLOW_PATH) import tensorflow as tf _tensorflow_model = tf.keras.models.load_model(str(TENSORFLOW_PATH), compile=False) return _tensorflow_model
def predict_pytorch(image: Image.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).squeeze().cpu().numpy()
sorted_indices = np.argsort(probs)[::-1] confidence = float(probs[sorted_indices[0]]) all_probs = [[CLASSES[i], float(probs[i])] for i in sorted_indices] predicted_class = "unknown" if confidence < CONFIDENCE_THRESHOLD else CLASSES[sorted_indices[0]] return predicted_class, confidence, all_probs
def predict_tensorflow(image: Image.Image): model = get_tensorflow_model() img = image.resize((130, 130)) arr = np.array(img, dtype=np.float32) / 255.0 arr = np.expand_dims(arr, 0) preds = model.predict(arr, verbose=0)[0] sorted_indices = np.argsort(preds)[::-1] confidence = float(preds[sorted_indices[0]]) all_probs = [[CLASSES[i], float(preds[i])] for i in sorted_indices] predicted_class = "unknown" if confidence < CONFIDENCE_THRESHOLD else CLASSES[sorted_indices[0]] return predicted_class, confidence, all_probs
def classify(image: Image.Image, model_choice: str): if model_choice == "pytorch": return predict_pytorch(image) return predict_tensorflow(image)
@app.get("/")def read_index(): index_path = BASE_DIR / "index.html" if not index_path.exists(): raise HTTPException(status_code=404, detail="index.html not found") return FileResponse(index_path, media_type="text/html")
@app.get("/health")def health_check(): return JSONResponse({"status": "ok"})
@app.post("/predict")def predict(image: UploadFile = File(...), model_choice: str = Form("pytorch")): if image.content_type.split('/')[0] != 'image': raise HTTPException(status_code=400, detail="Le fichier doit être une image.")
image_data = image.file.read() try: img = Image.open(io.BytesIO(image_data)).convert("RGB") except Exception as exc: raise HTTPException(status_code=400, detail=f"Impossible de lire l'image: {exc}")
predicted_class, confidence, all_probs = classify(img, model_choice) return { "predicted_class": predicted_class, "confidence": f"{confidence * 100:.2f}%", "probabilities": all_probs, }
if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=7860)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115<!DOCTYPE html><html lang="fr"><head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Intel Image Classifier</title> <style> body { font-family: Arial, sans-serif; background: #f4f7fb; color: #1f2937; margin: 0; padding: 0; } .container { max-width: 700px; margin: 3rem auto; padding: 2rem; background: white; border-radius: 16px; box-shadow: 0 20px 50px rgba(15,23,42,0.08); } h1 { margin-top: 0; font-size: 2rem; color: #111827; } p { line-height: 1.6; color: #374151; } .form-group { margin-bottom: 1.25rem; } label { display: block; margin-bottom: 0.5rem; font-weight: 600; } input[type="file"], select { width: 100%; padding: 0.8rem 1rem; border-radius: 0.75rem; border: 1px solid #d1d5db; background: #f9fafb; } button { border: none; background: #2563eb; color: white; padding: 0.9rem 1.4rem; border-radius: 0.9rem; font-weight: 700; cursor: pointer; transition: background 0.2s ease; } button:hover { background: #1d4ed8; } .result { margin-top: 1.5rem; padding: 1.2rem; border-radius: 1rem; background: #eff6ff; border: 1px solid #bfdbfe; } .result strong { display: inline-block; width: 170px; } .probabilities { margin-top: 1rem; width: 100%; border-collapse: collapse; } .probabilities th, .probabilities td { padding: 0.75rem 0.9rem; border-bottom: 1px solid #e5e7eb; text-align: left; } .spinner { display: none; margin-top: 1rem; color: #2563eb; } </style></head><body> <div class="container"> <h1>Intel Image Classifier</h1> <p>Déposez une image et choisissez un modèle pour obtenir une prédiction en temps réel.</p>
<form id="predict-form"> <div class="form-group"> <label for="image">Image</label> <input type="file" id="image" name="image" accept="image/*" required /> </div> <div class="form-group"> <label for="model-choice">Modèle</label> <select id="model-choice" name="model_choice"> <option value="pytorch">PyTorch</option> <option value="tensorflow">TensorFlow</option> </select> </div> <button type="submit">Classer l'image</button> <p class="spinner" id="spinner">Analyse en cours…</p> </form>
<div class="result" id="result" style="display:none;"> <p><strong>Classe prédite :</strong> <span id="predicted-class"></span></p> <p><strong>Confiance :</strong> <span id="confidence"></span></p> <div id="probabilities-container"></div> </div> </div>
<script> const form = document.getElementById('predict-form'); const spinner = document.getElementById('spinner'); const resultBox = document.getElementById('result'); const predictedClass = document.getElementById('predicted-class'); const confidence = document.getElementById('confidence'); const probabilitiesContainer = document.getElementById('probabilities-container');
form.addEventListener('submit', async (event) => { event.preventDefault(); const fileInput = document.getElementById('image'); const modelChoice = document.getElementById('model-choice').value; const file = fileInput.files[0];
if (!file) { alert('Veuillez sélectionner une image avant de soumettre.'); return; }
const formData = new FormData(); formData.append('image', file); formData.append('model_choice', modelChoice);
spinner.style.display = 'block'; resultBox.style.display = 'none'; probabilitiesContainer.innerHTML = '';
try { const response = await fetch('/predict', { method: 'POST', body: formData, });
if (!response.ok) { const errorText = await response.text(); throw new Error(errorText || 'Erreur serveur'); }
const data = await response.json(); predictedClass.textContent = data.predicted_class; confidence.textContent = data.confidence;
const table = document.createElement('table'); table.className = 'probabilities'; table.innerHTML = '<thead><tr><th>Classe</th><th>Probabilité</th></tr></thead>'; const tbody = document.createElement('tbody'); data.probabilities.forEach(item => { const row = document.createElement('tr'); row.innerHTML = `<td>${item[0]}</td><td>${(item[1] * 100).toFixed(2)}%</td>`; tbody.appendChild(row); }); table.appendChild(tbody); probabilitiesContainer.appendChild(table);
resultBox.style.display = 'block'; } catch (error) { alert('Erreur lors de la requête : ' + error.message); } finally { spinner.style.display = 'none'; } }); </script></body></html>123456789fastapiuvicorn[standard]python-multiparthuggingface_hubtorch>=2.2.0torchvision>=0.17.0tensorflow>=2.16.0numpy>=1.26.0pillow.gitignoreAdded+6
DockerfileAdded+11
README.mdAdded+37
app.pyAdded+189
index.htmlAdded+115
requirements.txtAdded+9