Adibrino commited on
Commit
21c4e6f
·
verified ·
1 Parent(s): a758f34

Upload 8 files

Browse files
Files changed (4) hide show
  1. README.md +5 -4
  2. README_DEPLOY.md +3 -4
  3. app.py +80 -39
  4. requirements.txt +2 -1
README.md CHANGED
@@ -1,12 +1,13 @@
1
  ---
2
  title: SMART POLDER-S3 Inference
3
- sdk: docker
4
- app_port: 7860
5
  ---
6
 
7
  # Hugging Face image inference service
8
 
9
- This is a Docker Space that exposes `POST /predict` for an SVGA camera JPEG.
 
10
  It runs the MobileNetV3-small classifier trained by `../Training/train.py`,
11
  using the ZeroGPU `spaces.GPU` decorator for inference.
12
  The ESP32 sends one JPEG frame directly to this endpoint for inference, then
@@ -25,7 +26,7 @@ model/
25
  ```
26
 
27
  The model files are intentionally not included in source control. Create a
28
- Docker Space on Hugging Face and upload this folder's files plus `model/`.
29
 
30
  ## Configure and test
31
 
 
1
  ---
2
  title: SMART POLDER-S3 Inference
3
+ sdk: gradio
4
+ app_file: app.py
5
  ---
6
 
7
  # Hugging Face image inference service
8
 
9
+ This Gradio Space exposes `POST /predict` for an SVGA camera JPEG and includes
10
+ a browser-based test interface.
11
  It runs the MobileNetV3-small classifier trained by `../Training/train.py`,
12
  using the ZeroGPU `spaces.GPU` decorator for inference.
13
  The ESP32 sends one JPEG frame directly to this endpoint for inference, then
 
26
  ```
27
 
28
  The model files are intentionally not included in source control. Create a
29
+ Gradio Space on Hugging Face and upload this folder's files plus `model/`.
30
 
31
  ## Configure and test
32
 
README_DEPLOY.md CHANGED
@@ -1,16 +1,15 @@
1
  # Deploy to Hugging Face
2
 
3
- 1. Create a **Docker Space** named `SMART POLDER-S3 Inference` on Hugging Face.
4
  2. Copy the output files from `AI/Training/output/` into this directory's
5
  `model/` subdirectory. `model.pt` and `classes.json` are required.
6
- 3. Upload `README.md`, `Dockerfile`, `app.py`, `requirements.txt`, and `model/`
7
- to the Space.
8
  4. Wait for the Space to build, then test `POST /predict` as shown in
9
  `README.md`.
10
  5. Keep the Space public for direct ESP32 access. Do not add a Hugging Face
11
  access token to the ESP32 firmware.
12
 
13
  SVGA describes the camera's source dimensions (800x600); the model applies the
14
- same 224x224 preprocessing used during validation. The app uses ZeroGPU via
15
  `spaces.GPU`; ZeroGPU queue and cold-start times can exceed the ESP32's
16
  four-second inference timeout. Measure actual end-to-end latency.
 
1
  # Deploy to Hugging Face
2
 
3
+ 1. Create a **Gradio Space** named `SMART POLDER-S3 Inference` on Hugging Face.
4
  2. Copy the output files from `AI/Training/output/` into this directory's
5
  `model/` subdirectory. `model.pt` and `classes.json` are required.
6
+ 3. Upload `README.md`, `app.py`, `requirements.txt`, and `model/` to the Space.
 
7
  4. Wait for the Space to build, then test `POST /predict` as shown in
8
  `README.md`.
9
  5. Keep the Space public for direct ESP32 access. Do not add a Hugging Face
10
  access token to the ESP32 firmware.
11
 
12
  SVGA describes the camera's source dimensions (800x600); the model applies the
13
+ same 224x224 preprocessing used during validation. The Gradio app uses ZeroGPU via
14
  `spaces.GPU`; ZeroGPU queue and cold-start times can exceed the ESP32's
15
  four-second inference timeout. Measure actual end-to-end latency.
app.py CHANGED
@@ -3,16 +3,19 @@ import json
3
  import os
4
  from pathlib import Path
5
 
 
 
6
  import torch
7
  from fastapi import FastAPI, HTTPException, Request
8
  from PIL import Image, ImageOps, UnidentifiedImageError
9
  from torchvision import models, transforms
10
- import spaces
11
 
12
  MODEL_DIR = Path(os.environ.get("MODEL_DIR", "model"))
13
  MAX_IMAGE_BYTES = 2 * 1024 * 1024
14
  MEAN = (0.485, 0.456, 0.406)
15
  STD = (0.229, 0.224, 0.225)
 
16
  def load_model():
17
  metadata_path = MODEL_DIR / "classes.json"
18
  weights_path = MODEL_DIR / "model.pt"
@@ -32,21 +35,24 @@ def load_model():
32
  ):
33
  raise RuntimeError("Invalid classes.json metadata")
34
 
35
- model = models.mobilenet_v3_small(weights=None)
36
- model.classifier[3] = torch.nn.Linear(model.classifier[3].in_features, len(classes))
 
 
37
  state = torch.load(weights_path, map_location="cpu", weights_only=True)
38
- model.load_state_dict(state)
39
- model.eval()
40
- return model, classes, image_size
41
 
42
  model, classes, image_size = load_model()
43
- preprocess = transforms.Compose([
44
- transforms.Resize(256),
45
- transforms.CenterCrop(image_size),
46
- transforms.ToTensor(),
47
- transforms.Normalize(MEAN, STD),
48
- ])
49
- app = FastAPI(title="SMART POLDER-S3 Inference")
 
50
 
51
  @spaces.GPU(duration=10)
52
  def run_inference(tensor):
@@ -57,46 +63,81 @@ def run_inference(tensor):
57
  finally:
58
  model.to("cpu")
59
 
 
 
 
 
 
 
 
 
 
 
60
 
61
- @app.get("/health")
62
- def health():
63
- return {"ok": True, "device": "zerogpu"}
64
-
65
- @app.post("/predict")
66
- async def predict(request: Request):
67
- content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
68
  if content_type != "image/jpeg":
69
- raise HTTPException(status_code=415, detail="Content-Type must be image/jpeg")
 
 
70
  content_length = request.headers.get("content-length")
71
- if content_length and content_length.isdigit() and int(content_length) > MAX_IMAGE_BYTES:
72
- raise HTTPException(status_code=413, detail="JPEG must be between 1 byte and 2 MiB")
 
 
 
 
 
 
 
73
  chunks = []
74
  size = 0
75
  async for chunk in request.stream():
76
  size += len(chunk)
77
  if size > MAX_IMAGE_BYTES:
78
- raise HTTPException(status_code=413, detail="JPEG must be between 1 byte and 2 MiB")
 
 
79
  chunks.append(chunk)
80
  if not size:
81
  raise HTTPException(status_code=400, detail="Empty JPEG image")
82
- body = b"".join(chunks)
83
  try:
84
- with Image.open(io.BytesIO(body)) as source:
85
  if source.format != "JPEG":
86
- raise HTTPException(status_code=415, detail="Payload is not a JPEG image")
 
 
87
  if source.width > 2048 or source.height > 2048:
88
- raise HTTPException(status_code=413, detail="JPEG dimensions must not exceed 2048x2048")
89
- image = ImageOps.exif_transpose(source).convert("RGB")
90
- tensor = preprocess(image).unsqueeze(0)
 
 
91
  except UnidentifiedImageError as exc:
92
  raise HTTPException(status_code=400, detail="Invalid JPEG image") from exc
93
 
94
- probabilities = run_inference(tensor)
95
- best_index = int(probabilities.argmax().item())
96
- label = classes[best_index]
97
- confidence = float(probabilities[best_index].item())
98
- return {
99
- "label": label,
100
- "confidence": confidence,
101
- "ai_trash_detected": label == "litter",
102
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import os
4
  from pathlib import Path
5
 
6
+ import gradio as gr
7
+ import spaces
8
  import torch
9
  from fastapi import FastAPI, HTTPException, Request
10
  from PIL import Image, ImageOps, UnidentifiedImageError
11
  from torchvision import models, transforms
12
+ import uvicorn
13
 
14
  MODEL_DIR = Path(os.environ.get("MODEL_DIR", "model"))
15
  MAX_IMAGE_BYTES = 2 * 1024 * 1024
16
  MEAN = (0.485, 0.456, 0.406)
17
  STD = (0.229, 0.224, 0.225)
18
+
19
  def load_model():
20
  metadata_path = MODEL_DIR / "classes.json"
21
  weights_path = MODEL_DIR / "model.pt"
 
35
  ):
36
  raise RuntimeError("Invalid classes.json metadata")
37
 
38
+ classifier = models.mobilenet_v3_small(weights=None)
39
+ classifier.classifier[3] = torch.nn.Linear(
40
+ classifier.classifier[3].in_features, len(classes)
41
+ )
42
  state = torch.load(weights_path, map_location="cpu", weights_only=True)
43
+ classifier.load_state_dict(state)
44
+ classifier.eval()
45
+ return classifier, classes, image_size
46
 
47
  model, classes, image_size = load_model()
48
+ preprocess = transforms.Compose(
49
+ [
50
+ transforms.Resize(256),
51
+ transforms.CenterCrop(image_size),
52
+ transforms.ToTensor(),
53
+ transforms.Normalize(MEAN, STD),
54
+ ]
55
+ )
56
 
57
  @spaces.GPU(duration=10)
58
  def run_inference(tensor):
 
63
  finally:
64
  model.to("cpu")
65
 
66
+ def classify(image):
67
+ tensor = preprocess(image.convert("RGB")).unsqueeze(0)
68
+ probabilities = run_inference(tensor)
69
+ best_index = int(probabilities.argmax().item())
70
+ label = classes[best_index]
71
+ return {
72
+ "label": label,
73
+ "confidence": float(probabilities[best_index].item()),
74
+ "ai_trash_detected": label == "litter",
75
+ }
76
 
77
+ async def read_jpeg(request):
78
+ content_type = (
79
+ request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
80
+ )
 
 
 
81
  if content_type != "image/jpeg":
82
+ raise HTTPException(
83
+ status_code=415, detail="Content-Type must be image/jpeg"
84
+ )
85
  content_length = request.headers.get("content-length")
86
+ if (
87
+ content_length
88
+ and content_length.isdigit()
89
+ and int(content_length) > MAX_IMAGE_BYTES
90
+ ):
91
+ raise HTTPException(
92
+ status_code=413, detail="JPEG must be between 1 byte and 2 MiB"
93
+ )
94
+
95
  chunks = []
96
  size = 0
97
  async for chunk in request.stream():
98
  size += len(chunk)
99
  if size > MAX_IMAGE_BYTES:
100
+ raise HTTPException(
101
+ status_code=413, detail="JPEG must be between 1 byte and 2 MiB"
102
+ )
103
  chunks.append(chunk)
104
  if not size:
105
  raise HTTPException(status_code=400, detail="Empty JPEG image")
106
+
107
  try:
108
+ with Image.open(io.BytesIO(b"".join(chunks))) as source:
109
  if source.format != "JPEG":
110
+ raise HTTPException(
111
+ status_code=415, detail="Payload is not a JPEG image"
112
+ )
113
  if source.width > 2048 or source.height > 2048:
114
+ raise HTTPException(
115
+ status_code=413,
116
+ detail="JPEG dimensions must not exceed 2048x2048",
117
+ )
118
+ return ImageOps.exif_transpose(source).convert("RGB")
119
  except UnidentifiedImageError as exc:
120
  raise HTTPException(status_code=400, detail="Invalid JPEG image") from exc
121
 
122
+ api = FastAPI(title="SMART POLDER-S3 Inference API")
123
+
124
+ @api.get("/health")
125
+ def health():
126
+ return {"ok": True, "device": "zerogpu"}
127
+
128
+ @api.post("/predict")
129
+ async def predict(request: Request):
130
+ return classify(await read_jpeg(request))
131
+
132
+ demo = gr.Interface(
133
+ fn=lambda image: classify(image),
134
+ inputs=gr.Image(type="pil", label="Unggah gambar"),
135
+ outputs=gr.JSON(label="Hasil klasifikasi"),
136
+ title="SMART POLDER-S3 Image Inference",
137
+ description="Klasifikasi gambar saluran menjadi clear atau litter.",
138
+ )
139
+
140
+ app = gr.mount_gradio_app(api, demo, path="/")
141
+
142
+ if __name__ == "__main__":
143
+ uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "7860")))
requirements.txt CHANGED
@@ -1,5 +1,6 @@
 
1
  fastapi>=0.110,<1
2
- uvicorn[standard]>=0.27,<1
3
  torch>=2.2
4
  torchvision>=0.17
5
  Pillow>=10.0
 
1
+ gradio>=5.0,<6
2
  fastapi>=0.110,<1
3
+ uvicorn>=0.27,<1
4
  torch>=2.2
5
  torchvision>=0.17
6
  Pillow>=10.0