Alex commited on
Commit
3b62419
·
1 Parent(s): 7077928

added endpoint

Browse files
Files changed (3) hide show
  1. README.md +12 -0
  2. app.py +42 -27
  3. woman_with_bag.jpeg +0 -0
README.md CHANGED
@@ -10,3 +10,15 @@ pinned: false
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
13
+
14
+
15
+ curl -X POST "https://alexgenovese-segmentation.hf.space/api/predict" \
16
+ -F "data=[{\"type\": \"image\", \"value\": null}]" \
17
+ -F "data=@woman_with_bag.jpeg" \
18
+ -H "Content-Type: multipart/form-data" \
19
+ -o response.json
20
+
21
+
22
+ curl -X POST "https://alexgenovese-segmentation.hf.space/api/predict" \
23
+ -F "data=[{\"type\": \"image\", \"value\": null}]" \
24
+ -F "data=@woman_with_bag.jpeg" \
app.py CHANGED
@@ -1,48 +1,63 @@
1
- import gradio as gr
2
  from transformers import SamModel, SamProcessor
 
3
  from PIL import Image
4
  import numpy as np
5
- import torch
 
6
 
7
- # Carica il modello e il processore
 
 
 
8
  model = SamModel.from_pretrained("facebook/sam-vit-base")
9
  processor = SamProcessor.from_pretrained("facebook/sam-vit-base")
10
- model.to("cpu") # Assicurati che il modello giri su CPU
11
 
12
- def segment_image(image):
13
- # Converti l'immagine in formato compatibile
14
- img = Image.fromarray(np.uint8(image)).convert("RGB")
15
-
16
- # Prepara l'input per SAM (segmentazione automatica)
17
- inputs = processor(img, return_tensors="pt").to("cpu")
18
 
19
  # Inferenza
20
  with torch.no_grad():
21
  outputs = model(**inputs, multimask_output=False)
22
 
23
- # Post-processa per ottenere la maschera
24
  mask = processor.image_processor.post_process_masks(
25
  outputs.pred_masks, inputs["original_sizes"], inputs["reshaped_input_sizes"]
26
  )[0][0].cpu().numpy()
27
 
28
- # Converti la maschera in un'immagine visibile
29
  mask_img = Image.fromarray((mask * 255).astype(np.uint8))
30
 
31
- # Annotazioni (es. bounding box o etichette semplici)
32
- annotations = {"mask": mask.tolist(), "label": "object"} # Personalizza come necessario
 
 
33
 
34
- return mask_img, str(annotations)
 
 
 
35
 
36
- # Interfaccia Gradio
37
- interface = gr.Interface(
38
- fn=segment_image,
39
- inputs=gr.Image(type="numpy", label="Carica un'immagine"),
40
- outputs=[
41
- gr.Image(type="pil", label="Maschera di segmentazione"),
42
- gr.Textbox(label="Annotazioni per inpainting")
43
- ],
44
- title="Segmentazione di vestiti e oggetti con SAM",
45
- description="Carica un'immagine per ottenere la segmentazione e le annotazioni."
46
- )
 
 
 
 
47
 
48
- interface.launch()
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile
2
  from transformers import SamModel, SamProcessor
3
+ import torch
4
  from PIL import Image
5
  import numpy as np
6
+ import io
7
+ import base64
8
 
9
+ # Inizializza l'app FastAPI
10
+ app = FastAPI()
11
+
12
+ # Carica il modello e il processore SAM
13
  model = SamModel.from_pretrained("facebook/sam-vit-base")
14
  processor = SamProcessor.from_pretrained("facebook/sam-vit-base")
15
+ model.to("cpu") # Usa CPU per il free tier
16
 
17
+ # Funzione per segmentare l'immagine
18
+ def segment_image(image: Image.Image):
19
+ # Prepara l'input per SAM
20
+ inputs = processor(image, return_tensors="pt").to("cpu")
 
 
21
 
22
  # Inferenza
23
  with torch.no_grad():
24
  outputs = model(**inputs, multimask_output=False)
25
 
26
+ # Post-processa la maschera
27
  mask = processor.image_processor.post_process_masks(
28
  outputs.pred_masks, inputs["original_sizes"], inputs["reshaped_input_sizes"]
29
  )[0][0].cpu().numpy()
30
 
31
+ # Converti la maschera in immagine
32
  mask_img = Image.fromarray((mask * 255).astype(np.uint8))
33
 
34
+ # Converti la maschera in base64 per la risposta
35
+ buffered = io.BytesIO()
36
+ mask_img.save(buffered, format="PNG")
37
+ mask_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
38
 
39
+ # Annotazioni
40
+ annotations = {"mask": mask.tolist(), "label": "object"}
41
+
42
+ return mask_base64, annotations
43
 
44
+ # Endpoint API
45
+ @app.post("/segment")
46
+ async def segment_endpoint(file: UploadFile = File(...)):
47
+ # Leggi l'immagine caricata
48
+ image_data = await file.read()
49
+ image = Image.open(io.BytesIO(image_data)).convert("RGB")
50
+
51
+ # Segmenta l'immagine
52
+ mask_base64, annotations = segment_image(image)
53
+
54
+ # Restituisci la risposta
55
+ return {
56
+ "mask": f"data:image/png;base64,{mask_base64}",
57
+ "annotations": annotations
58
+ }
59
 
60
+ # Per compatibilità con Hugging Face Spaces (Uvicorn viene gestito automaticamente)
61
+ if __name__ == "__main__":
62
+ import uvicorn
63
+ uvicorn.run(app, host="0.0.0.0", port=7860)
woman_with_bag.jpeg ADDED