Hasthika commited on
Commit
9c3faeb
·
verified ·
1 Parent(s): 935d1f8

New U2net Rem Bg Model

Browse files
Files changed (2) hide show
  1. main.py +45 -24
  2. requirements.txt +2 -0
main.py CHANGED
@@ -68,37 +68,58 @@ def generate_depth_map(input_path: str, output_path: str):
68
  print(f"Depth generation failed: {e}")
69
  return False
70
 
71
- def remove_background(input_path: str, output_path: str):
72
- """Uses Remove.bg API to remove background from an image."""
73
- api_key = os.getenv("REMOVE_BG_API_KEY")
74
- if not api_key or api_key == "your_api_key_here":
75
- # Fallback/simulation if no key is provided yet
76
- print(f"Warning: No valid REMOVE_BG_API_KEY found. Simulating background removal for {input_path}")
77
- shutil.copy(input_path, output_path)
78
- return True
 
 
 
 
 
 
 
 
 
 
79
 
 
 
80
  try:
81
- with open(input_path, 'rb') as f:
82
- response = requests.post(
83
- 'https://api.remove.bg/v1.0/removebg',
84
- files={'image_file': f},
85
- data={'size': 'auto'},
86
- headers={'X-Api-Key': api_key},
87
- )
88
 
89
- if response.status_code == requests.codes.ok:
90
- with open(output_path, 'wb') as out:
91
- out.write(response.content)
 
 
 
 
 
92
  return True
93
  else:
94
- print(f"Error from Remove.bg: {response.status_code} - {response.text}")
95
- return False
 
 
96
  except Exception as e:
97
- print(f"Request failed: {e}")
98
- return False
 
 
 
 
 
 
 
99
 
100
  from fastapi import BackgroundTasks
101
- from typing import Dict, Any
102
 
103
  # Simple in-memory storage for job status
104
  # In production, this would be a database (Redis/Postgres)
@@ -157,7 +178,7 @@ async def process_dish_photos(
157
  background_tasks: BackgroundTasks,
158
  shop_slug: str = Form(...),
159
  category: str = Form("uncategorized"),
160
- files: list[UploadFile] = File(...)
161
  ):
162
  """
163
  Receives 12 photos of a dish, saves them, and starts the 2.5D processing pipeline in the background.
 
68
  print(f"Depth generation failed: {e}")
69
  return False
70
 
71
+ # remove_bg_exhausted boolean no longer needed since we use local AI
72
+
73
+ # Initialize local AI session once globally to avoid reloading the model on every image
74
+ rmbg_session = None
75
+
76
+ def get_rmbg_session():
77
+ global rmbg_session
78
+ if rmbg_session is None:
79
+ try:
80
+ from rembg import new_session
81
+ # Using the default u2net model which offers exceptional quality
82
+ # equivalent to RMBG-1.4 but strictly compatible with this environment
83
+ print("Loading local AI background removal model... (this may take a minute on first run)")
84
+ rmbg_session = new_session('u2net')
85
+ print("Local AI Background removal model loaded successfully!")
86
+ except Exception as e:
87
+ print(f"Failed to load local AI background remover: {e}")
88
+ return rmbg_session
89
 
90
+ def remove_background(input_path: str, output_path: str):
91
+ """Uses local AI (rembg/u2net) to remove background from an image. No API keys needed!"""
92
  try:
93
+ from PIL import Image
94
+ from rembg import remove
 
 
 
 
 
95
 
96
+ img = Image.open(input_path)
97
+ session = get_rmbg_session()
98
+
99
+ if session:
100
+ # Remove background locally
101
+ result = remove(img, session=session)
102
+ # Save as PNG to keep transparency
103
+ result.save(output_path, format="PNG")
104
  return True
105
  else:
106
+ # Fallback if session couldn't be loaded
107
+ img.save(output_path, format="PNG")
108
+ return True
109
+
110
  except Exception as e:
111
+ print(f"Local AI Background removal failed: {e}")
112
+ # Graceful fallback to copy
113
+ try:
114
+ from PIL import Image
115
+ img = Image.open(input_path)
116
+ img.save(output_path, format="PNG")
117
+ except:
118
+ shutil.copy(input_path, output_path)
119
+ return True
120
 
121
  from fastapi import BackgroundTasks
122
+ from typing import Dict, Any, List
123
 
124
  # Simple in-memory storage for job status
125
  # In production, this would be a database (Redis/Postgres)
 
178
  background_tasks: BackgroundTasks,
179
  shop_slug: str = Form(...),
180
  category: str = Form("uncategorized"),
181
+ files: List[UploadFile] = File(...)
182
  ):
183
  """
184
  Receives 12 photos of a dish, saves them, and starts the 2.5D processing pipeline in the background.
requirements.txt CHANGED
@@ -4,5 +4,7 @@ python-multipart==0.0.9
4
  requests==2.32.3
5
  python-dotenv==1.0.1
6
  torch
 
7
  transformers
8
  Pillow
 
 
4
  requests==2.32.3
5
  python-dotenv==1.0.1
6
  torch
7
+ torchvision
8
  transformers
9
  Pillow
10
+ scikit-image