VINU NAYAK commited on
Commit
4deeed2
·
verified ·
1 Parent(s): d6b2356

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -1
app.py CHANGED
@@ -1,6 +1,92 @@
1
  # Import app from main.py for actual background removal
2
  try:
3
- from main import app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  except ImportError:
5
  # Fallback to the simple version if the main version fails
6
  from fallback import app
 
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