omthakur1 commited on
Commit
15c1025
Β·
0 Parent(s):

Initial commit: HF Spaces deployment with u2net model

Browse files
Files changed (5) hide show
  1. .gitignore +30 -0
  2. Dockerfile +23 -0
  3. README.md +65 -0
  4. app.py +106 -0
  5. requirements.txt +4 -0
.gitignore ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+
8
+ # Virtual environment
9
+ venv/
10
+ env/
11
+ ENV/
12
+
13
+ # IDE
14
+ .vscode/
15
+ .idea/
16
+ *.swp
17
+ *.swo
18
+
19
+ # OS
20
+ .DS_Store
21
+ Thumbs.db
22
+
23
+ # Testing
24
+ .pytest_cache/
25
+ .coverage
26
+ htmlcov/
27
+
28
+ # Local env files
29
+ .env
30
+ .env.local
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Install system dependencies needed for OpenCV and image processing
6
+ RUN apt-get update && apt-get install -y --no-install-recommends \
7
+ libgl1 \
8
+ libglib2.0-0 \
9
+ && apt-get clean \
10
+ && rm -rf /var/lib/apt/lists/*
11
+
12
+ # Copy requirements and install Python dependencies
13
+ COPY requirements.txt .
14
+ RUN pip install --no-cache-dir -r requirements.txt
15
+
16
+ # Copy application code
17
+ COPY app.py .
18
+
19
+ # Expose port 7860 (Hugging Face Spaces default)
20
+ EXPOSE 7860
21
+
22
+ # Run the Flask app
23
+ CMD ["python", "app.py"]
README.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Background Removal API
3
+ emoji: 🎨
4
+ colorFrom: purple
5
+ colorTo: blue
6
+ sdk: docker
7
+ pinned: false
8
+ license: mit
9
+ ---
10
+
11
+ # 🎨 Background Removal API
12
+
13
+ **FREE forever** AI-powered background removal API using rembg.
14
+
15
+ ## Features
16
+
17
+ - βœ… **100% FREE** - No API keys, no limits
18
+ - πŸš€ **Fast** - Optimized u2netp model
19
+ - 🎯 **High Quality** - Professional results
20
+ - πŸ”“ **No Authentication** - Ready to use
21
+ - ♾️ **Unlimited** - Process as many images as you need
22
+
23
+ ## API Endpoints
24
+
25
+ ### POST /remove-background
26
+ Upload an image and get back a PNG with transparent background.
27
+
28
+ **Example (curl):**
29
+ ```bash
30
+ curl -X POST https://YOUR_SPACE.hf.space/remove-background \
31
+ -F "image=@your-image.jpg" \
32
+ -o output.png
33
+ ```
34
+
35
+ **Example (JavaScript):**
36
+ ```javascript
37
+ const formData = new FormData();
38
+ formData.append('image', fileInput.files[0]);
39
+
40
+ const response = await fetch('https://YOUR_SPACE.hf.space/remove-background', {
41
+ method: 'POST',
42
+ body: formData
43
+ });
44
+
45
+ const blob = await response.blob();
46
+ ```
47
+
48
+ ### GET /health
49
+ Check if API is running.
50
+
51
+ ## Technology
52
+
53
+ - **rembg** - AI background removal
54
+ - **u2netp** - Lightweight, fast model
55
+ - **Flask** - Python web framework
56
+ - **Hugging Face Spaces** - FREE hosting forever
57
+
58
+ ## Deploy Your Own
59
+
60
+ 1. Create account on https://huggingface.co
61
+ 2. Create new Space (SDK: Docker)
62
+ 3. Upload these files
63
+ 4. πŸŽ‰ Done! Your API is live
64
+
65
+ Built with ❀️ for the community
app.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Background Removal API for Hugging Face Spaces
3
+ Self-hosted, FREE forever with unlimited usage!
4
+ """
5
+ from flask import Flask, request, send_file
6
+ from flask_cors import CORS
7
+ from rembg import remove, new_session
8
+ from PIL import Image
9
+ import io
10
+ import os
11
+
12
+ app = Flask(__name__)
13
+
14
+ # Allow CORS from your Vercel domain
15
+ CORS(app, origins=["*"]) # In production, replace * with your Vercel domain
16
+
17
+ # Global session variable
18
+ _session = None
19
+
20
+ def get_session():
21
+ """Lazy load rembg session on first use"""
22
+ global _session
23
+ if _session is None:
24
+ print("πŸ”§ Initializing rembg session with u2net model...")
25
+ try:
26
+ _session = new_session("u2net")
27
+ print("βœ… Session initialized successfully!")
28
+ except Exception as e:
29
+ print(f"❌ Session init error: {e}")
30
+ raise
31
+ return _session
32
+
33
+ @app.route('/')
34
+ def root():
35
+ """Root endpoint with API info"""
36
+ return {
37
+ 'name': 'Background Removal API',
38
+ 'version': '2.1.0',
39
+ 'backend': 'Self-hosted rembg (u2net model - High Quality)',
40
+ 'platform': 'Hugging Face Spaces',
41
+ 'features': '100% FREE forever, Unlimited usage, No API keys needed',
42
+ 'endpoints': {
43
+ 'POST /remove-background': 'Remove background from image',
44
+ 'GET /health': 'Health check'
45
+ }
46
+ }, 200
47
+
48
+ @app.route('/health')
49
+ def health_check():
50
+ """Health check endpoint"""
51
+ return {
52
+ 'status': 'ok',
53
+ 'message': 'Background removal API is running',
54
+ 'backend': 'Self-hosted rembg with u2net model (High Quality)',
55
+ 'platform': 'Hugging Face Spaces (FREE forever)'
56
+ }, 200
57
+
58
+ @app.route('/remove-background', methods=['POST'])
59
+ def remove_background():
60
+ """
61
+ Background removal using rembg with u2netp model
62
+ NO external APIs - 100% self-hosted!
63
+ """
64
+ try:
65
+ # Get uploaded file
66
+ if 'image' not in request.files:
67
+ return {'error': 'No image file provided'}, 400
68
+
69
+ file = request.files['image']
70
+ input_image = Image.open(file.stream)
71
+
72
+ print(f"🎨 Processing image: {file.filename}")
73
+ print(f"πŸ“ Size: {input_image.size}")
74
+
75
+ # Get session and remove background
76
+ session = get_session()
77
+ output_image = remove(input_image, session=session)
78
+
79
+ print(f"βœ… Background removed successfully!")
80
+
81
+ # Convert to PNG bytes
82
+ img_io = io.BytesIO()
83
+ output_image.save(img_io, 'PNG', optimize=False)
84
+ img_io.seek(0)
85
+
86
+ return send_file(
87
+ img_io,
88
+ mimetype='image/png',
89
+ as_attachment=True,
90
+ download_name=f"{file.filename.rsplit('.', 1)[0]}-nobg.png"
91
+ )
92
+
93
+ except Exception as e:
94
+ print(f"❌ Error: {str(e)}")
95
+ import traceback
96
+ traceback.print_exc()
97
+ return {'error': str(e)}, 500
98
+
99
+ if __name__ == '__main__':
100
+ port = int(os.environ.get('PORT', 7860)) # HF Spaces uses port 7860
101
+ print("πŸš€ Background Removal API starting on Hugging Face Spaces...")
102
+ print(f"πŸ“ Running on port {port}")
103
+ print("βœ… Using self-hosted rembg (NO external APIs!)")
104
+ print("🎯 Model: u2netp (optimized for quality)")
105
+ print("πŸ†“ FREE forever - Unlimited usage!")
106
+ app.run(host='0.0.0.0', port=port, debug=False)
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ flask==3.0.0
2
+ flask-cors==4.0.0
3
+ rembg[cpu]==2.0.72
4
+ pillow>=10.4.0