VINU NAYAK commited on
Commit
77fcd4c
·
verified ·
1 Parent(s): 9ed6dd5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -91
app.py CHANGED
@@ -1,95 +1,63 @@
1
- # Import app from main.py for actual background removal
2
- try:
3
- from main import app as main_app
4
- import os
5
- import secrets
6
- import json
7
- import uuid
8
- from fastapi import FastAPI, Depends, HTTPException, Header, status, File, UploadFile
9
-
10
- # Create the FastAPI app
11
- app = FastAPI(title="Background Removal API with API Key Support")
12
-
13
- # API key storage file
14
- API_KEYS_FILE = "api_keys.json"
15
-
16
- # Initialize API keys from file or create default
17
- def init_api_keys():
18
- if os.path.exists(API_KEYS_FILE):
19
- try:
20
- with open(API_KEYS_FILE, "r") as f:
21
- return json.load(f)
22
- except:
23
- # If file is corrupted, create new
24
- pass
25
-
26
- # Generate a default API key if none exists
27
- default_key = secrets.token_urlsafe(16)
28
- keys = {"default": {"key": default_key, "active": True}}
29
- with open(API_KEYS_FILE, "w") as f:
30
- json.dump(keys, f)
31
- print(f"Created default API key: {default_key}")
32
- return keys
33
-
34
- # API keys dictionary
35
- API_KEYS = init_api_keys()
36
-
37
- # Function to verify API key
38
- def verify_api_key(api_key: str = Header(None, alias="X-API-Key")):
39
- if api_key is None:
40
- raise HTTPException(
41
- status_code=status.HTTP_401_UNAUTHORIZED,
42
- detail="API key is missing"
43
- )
44
-
45
- for key_info in API_KEYS.values():
46
- if key_info["key"] == api_key and key_info["active"]:
47
- return True
48
-
49
- raise HTTPException(
50
- status_code=status.HTTP_401_UNAUTHORIZED,
51
- detail="Invalid API key"
52
- )
53
 
54
- # Root endpoint
55
- @app.get("/")
56
- async def root():
57
- return {
58
- "message": "Background Removal API with API Key Support",
59
- "docs": "/docs",
60
- "endpoints": ["/remove-bg", "/api-key"]
61
- }
62
 
63
- # Generate API key endpoint
64
- @app.get("/api-key")
65
- async def generate_api_key():
66
- new_key = secrets.token_urlsafe(16)
67
- key_id = str(uuid.uuid4())[:8]
68
- API_KEYS[key_id] = {"key": new_key, "active": True}
69
 
70
- # Save to file
71
- with open(API_KEYS_FILE, "w") as f:
72
- json.dump(API_KEYS, f)
73
-
74
- return {"api_key": new_key, "message": "Keep this key secure. You'll need it for API calls."}
75
-
76
- # Import the background removal function from main
77
- from main import remove_background
78
-
79
- # Protect the remove-bg endpoint with API key
80
- @app.post("/remove-bg")
81
- async def protected_remove_background(api_key_valid: bool = Depends(verify_api_key), file: UploadFile = File(...)):
82
- # Forward to the original function
83
- return await remove_background(file=file)
84
-
85
- # Print the default API key for testing
86
- if "default" in API_KEYS:
87
- print(f"Default API key for testing: {API_KEYS['default']['key']}")
88
- print(f"To use: Add 'X-API-Key: {API_KEYS['default']['key']}' to your request headers")
89
-
90
- except ImportError:
91
- # Fallback to the simple version if the main version fails
92
- from fallback import app
93
 
94
- # This ensures the "app" variable is properly exported for ASGI
95
- # This file ensures compatibility with both app:app and main:app entrypoints
 
1
+ from flask import Flask, request, jsonify, send_file
2
+ from rembg import remove
3
+ from PIL import Image
4
+ import io
5
+ import os
6
+ from dotenv import load_dotenv
7
+
8
+ # Load environment variables
9
+ load_dotenv()
10
+
11
+ app = Flask(__name__)
12
+
13
+ # Get API key from environment variable
14
+ API_KEY = os.getenv('API_KEY')
15
+
16
+ def check_api_key():
17
+ api_key = request.headers.get('X-API-Key')
18
+ if not api_key or api_key != API_KEY:
19
+ return False
20
+ return True
21
+
22
+ @app.route('/remove-bg', methods=['POST'])
23
+ def remove_background():
24
+ # Check API key
25
+ if not check_api_key():
26
+ return jsonify({'error': 'Invalid or missing API key'}), 401
27
+
28
+ if 'image' not in request.files:
29
+ return jsonify({'error': 'No image file provided'}), 400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ file = request.files['image']
 
 
 
 
 
 
 
32
 
33
+ if file.filename == '':
34
+ return jsonify({'error': 'No selected file'}), 400
35
+
36
+ try:
37
+ # Read the image
38
+ input_image = Image.open(file.stream)
39
 
40
+ # Remove background
41
+ output = remove(input_image)
42
+
43
+ # Save to bytes
44
+ img_byte_arr = io.BytesIO()
45
+ output.save(img_byte_arr, format='PNG')
46
+ img_byte_arr.seek(0)
47
+
48
+ return send_file(
49
+ img_byte_arr,
50
+ mimetype='image/png',
51
+ as_attachment=True,
52
+ download_name='removed_bg.png'
53
+ )
54
+
55
+ except Exception as e:
56
+ return jsonify({'error': str(e)}), 500
57
+
58
+ @app.route('/health', methods=['GET'])
59
+ def health_check():
60
+ return jsonify({'status': 'healthy'}), 200
 
 
61
 
62
+ if __name__ == '__main__':
63
+ app.run(host='0.0.0.0', port=5000)