aliroohan179 commited on
Commit
560d4b2
·
1 Parent(s): 7bc83e3
Files changed (1) hide show
  1. main.py +34 -10
main.py CHANGED
@@ -1,6 +1,7 @@
1
  from fastapi import FastAPI, File, UploadFile, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.responses import JSONResponse
 
4
  from pydantic import BaseModel
5
  from typing import List, Optional
6
  import numpy as np
@@ -11,6 +12,7 @@ import base64
11
  import os
12
  from pathlib import Path
13
  import torch
 
14
  from sam2.build_sam import build_sam2
15
  from sam2.sam2_image_predictor import SAM2ImagePredictor
16
  from dotenv import load_dotenv
@@ -19,6 +21,13 @@ load_dotenv()
19
 
20
  app = FastAPI(title="SAM 2 Image Segmentation API")
21
 
 
 
 
 
 
 
 
22
  # CORS middleware
23
  app.add_middleware(
24
  CORSMiddleware,
@@ -32,6 +41,7 @@ app.add_middleware(
32
  sam_predictor: Optional[SAM2ImagePredictor] = None
33
  current_image: Optional[np.ndarray] = None
34
  current_image_embeddings = None
 
35
 
36
  # Models
37
  class Point(BaseModel):
@@ -95,14 +105,26 @@ async def root():
95
  @app.post("/upload-image")
96
  async def upload_image(file: UploadFile = File(...)):
97
  """Upload and process an image for segmentation"""
98
- global current_image, current_image_embeddings, sam_predictor
99
 
100
  if sam_predictor is None:
101
  raise HTTPException(status_code=503, detail="SAM model not initialized")
102
 
103
  try:
104
- # Read image
105
  contents = await file.read()
 
 
 
 
 
 
 
 
 
 
 
 
106
  image = Image.open(io.BytesIO(contents))
107
 
108
  # Convert to RGB if needed
@@ -115,15 +137,9 @@ async def upload_image(file: UploadFile = File(...)):
115
  # Generate embeddings
116
  sam_predictor.set_image(current_image)
117
 
118
- # Convert image to base64 for response
119
- img_byte_arr = io.BytesIO()
120
- image.save(img_byte_arr, format='PNG')
121
- img_byte_arr = img_byte_arr.getvalue()
122
- img_base64 = base64.b64encode(img_byte_arr).decode('utf-8')
123
-
124
  return JSONResponse({
125
  "message": "Image uploaded successfully",
126
- "image": f"data:image/png;base64,{img_base64}",
127
  "width": current_image.shape[1],
128
  "height": current_image.shape[0]
129
  })
@@ -189,10 +205,18 @@ async def generate_mask(request: MaskRequest):
189
  @app.post("/reset")
190
  async def reset():
191
  """Reset current image and embeddings"""
192
- global current_image, current_image_embeddings
 
 
 
 
 
 
 
193
 
194
  current_image = None
195
  current_image_embeddings = None
 
196
 
197
  return {"message": "Reset successful"}
198
 
 
1
  from fastapi import FastAPI, File, UploadFile, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.responses import JSONResponse
4
+ from fastapi.staticfiles import StaticFiles
5
  from pydantic import BaseModel
6
  from typing import List, Optional
7
  import numpy as np
 
12
  import os
13
  from pathlib import Path
14
  import torch
15
+ import uuid
16
  from sam2.build_sam import build_sam2
17
  from sam2.sam2_image_predictor import SAM2ImagePredictor
18
  from dotenv import load_dotenv
 
21
 
22
  app = FastAPI(title="SAM 2 Image Segmentation API")
23
 
24
+ # Create uploads directory for storing original images
25
+ UPLOAD_DIR = Path("tmp")
26
+ UPLOAD_DIR.mkdir(exist_ok=True)
27
+
28
+ # Mount static files to serve uploaded images
29
+ app.mount("/tmp", StaticFiles(directory="tmp"), name="tmp")
30
+
31
  # CORS middleware
32
  app.add_middleware(
33
  CORSMiddleware,
 
41
  sam_predictor: Optional[SAM2ImagePredictor] = None
42
  current_image: Optional[np.ndarray] = None
43
  current_image_embeddings = None
44
+ current_image_path: Optional[str] = None # Path to the original uploaded image
45
 
46
  # Models
47
  class Point(BaseModel):
 
105
  @app.post("/upload-image")
106
  async def upload_image(file: UploadFile = File(...)):
107
  """Upload and process an image for segmentation"""
108
+ global current_image, current_image_embeddings, current_image_path, sam_predictor
109
 
110
  if sam_predictor is None:
111
  raise HTTPException(status_code=503, detail="SAM model not initialized")
112
 
113
  try:
114
+ # Read original bytes
115
  contents = await file.read()
116
+
117
+ # Save original file to disk (preserves exact quality)
118
+ file_ext = Path(file.filename).suffix if file.filename else ".png"
119
+ unique_filename = f"{uuid.uuid4()}{file_ext}"
120
+ file_path = UPLOAD_DIR / unique_filename
121
+
122
+ with open(file_path, "wb") as f:
123
+ f.write(contents)
124
+
125
+ current_image_path = str(file_path)
126
+
127
+ # Load image for processing
128
  image = Image.open(io.BytesIO(contents))
129
 
130
  # Convert to RGB if needed
 
137
  # Generate embeddings
138
  sam_predictor.set_image(current_image)
139
 
 
 
 
 
 
 
140
  return JSONResponse({
141
  "message": "Image uploaded successfully",
142
+ "image_url": f"/tmp/{unique_filename}",
143
  "width": current_image.shape[1],
144
  "height": current_image.shape[0]
145
  })
 
205
  @app.post("/reset")
206
  async def reset():
207
  """Reset current image and embeddings"""
208
+ global current_image, current_image_embeddings, current_image_path
209
+
210
+ # Delete the uploaded file if it exists
211
+ if current_image_path and os.path.exists(current_image_path):
212
+ try:
213
+ os.remove(current_image_path)
214
+ except OSError:
215
+ pass # Ignore deletion errors
216
 
217
  current_image = None
218
  current_image_embeddings = None
219
+ current_image_path = None
220
 
221
  return {"message": "Reset successful"}
222