File size: 8,484 Bytes
60c56d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
"""
FastAPI application for image colorization using ColorizeNet model
with Firebase App Check integration
"""
import os
import uuid
import logging
from pathlib import Path
from typing import Optional
from fastapi import FastAPI, File, UploadFile, HTTPException, Depends, Request
from fastapi.responses import FileResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
import firebase_admin
from firebase_admin import credentials, app_check
import cv2
import numpy as np
import torch
from PIL import Image
import io

from app.colorize_model import ColorizeModel
from app.config import settings

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Initialize FastAPI app
app = FastAPI(
    title="Colorize API",
    description="Image colorization API using ColorizeNet model",
    version="1.0.0"
)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Configure appropriately for production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize Firebase Admin SDK
firebase_cred_path = os.getenv("FIREBASE_CREDENTIALS_PATH", "colorize-662df-firebase-adminsdk-fbsvc-e080668793.json")
if os.path.exists(firebase_cred_path):
    try:
        cred = credentials.Certificate(firebase_cred_path)
        firebase_admin.initialize_app(cred)
        logger.info("Firebase Admin SDK initialized")
    except Exception as e:
        logger.warning("Failed to initialize Firebase: %s", str(e))
        firebase_admin.initialize_app()
else:
    logger.warning("Firebase credentials file not found. App Check will be disabled.")
    try:
        firebase_admin.initialize_app()
    except:
        pass

# Create directories
UPLOAD_DIR = Path("uploads")
RESULT_DIR = Path("results")
UPLOAD_DIR.mkdir(exist_ok=True)
RESULT_DIR.mkdir(exist_ok=True)

# Mount static files for serving results
app.mount("/results", StaticFiles(directory="results"), name="results")
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")

# Initialize ColorizeNet model
colorize_model = None

@app.on_event("startup")
async def startup_event():
    """Initialize the colorization model on startup"""
    global colorize_model
    try:
        logger.info("Loading ColorizeNet model...")
        colorize_model = ColorizeModel()
        logger.info("ColorizeNet model loaded successfully")
    except Exception as e:
        logger.error("Failed to load ColorizeNet model: %s", str(e))
        # Don't raise - allow health check to work even if model fails

@app.on_event("shutdown")
async def shutdown_event():
    """Cleanup on shutdown"""
    global colorize_model
    if colorize_model:
        del colorize_model
    logger.info("Application shutdown")

# Firebase App Check verification
async def verify_app_check(request: Request):
    """Verify Firebase App Check token"""
    if not settings.ENABLE_APP_CHECK:
        return True
    
    app_check_token = request.headers.get("X-Firebase-AppCheck")
    if not app_check_token:
        raise HTTPException(
            status_code=401,
            detail="Missing App Check token"
        )
    
    try:
        # Verify the App Check token
        app_check_claims = app_check.verify_token(app_check_token)
        logger.info("App Check token verified for: %s", app_check_claims.get("app_id"))
        return True
    except Exception as e:
        logger.warning("App Check token verification failed: %s", str(e))
        raise HTTPException(
            status_code=401,
            detail="Invalid App Check token"
        )

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {
        "status": "healthy",
        "model_loaded": colorize_model is not None
    }

@app.post("/upload")
async def upload_image(
    file: UploadFile = File(...),
    verified: bool = Depends(verify_app_check)
):
    """
    Upload an image and return the uploaded image URL
    """
    if not file.content_type or not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="File must be an image")
    
    # Generate unique filename
    file_id = str(uuid.uuid4())
    file_extension = Path(file.filename).suffix or ".jpg"
    filename = f"{file_id}{file_extension}"
    filepath = UPLOAD_DIR / filename
    
    # Save uploaded file
    try:
        contents = await file.read()
        with open(filepath, "wb") as f:
            f.write(contents)
        logger.info("Image uploaded: %s", filename)
        
        # Return the URL to access the uploaded image
        base_url = os.getenv("BASE_URL", os.getenv("SPACE_HOST", "http://localhost:7860"))
        image_url = f"{base_url}/uploads/{filename}"
        
        return {
            "success": True,
            "image_id": file_id,
            "image_url": image_url,
            "filename": filename
        }
    except Exception as e:
        logger.error("Error uploading image: %s", str(e))
        raise HTTPException(status_code=500, detail=f"Error uploading image: {str(e)}")

@app.post("/colorize")
async def colorize_image(
    file: UploadFile = File(...),
    verified: bool = Depends(verify_app_check)
):
    """
    Colorize an uploaded grayscale image using ColorizeNet
    Returns the colorized image URL
    """
    if colorize_model is None:
        raise HTTPException(status_code=503, detail="Colorization model not loaded")
    
    if not file.content_type or not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="File must be an image")
    
    try:
        # Read image
        contents = await file.read()
        image = Image.open(io.BytesIO(contents))
        
        # Convert to RGB if needed
        if image.mode != "RGB":
            image = image.convert("RGB")
        
        # Colorize the image
        logger.info("Colorizing image...")
        colorized_image = colorize_model.colorize(image)
        
        # Save colorized image
        file_id = str(uuid.uuid4())
        result_filename = f"{file_id}.jpg"
        result_filepath = RESULT_DIR / result_filename
        
        colorized_image.save(result_filepath, "JPEG", quality=95)
        logger.info("Colorized image saved: %s", result_filename)
        
        # Return URLs
        base_url = os.getenv("BASE_URL", os.getenv("SPACE_HOST", "http://localhost:7860"))
        download_url = f"{base_url}/results/{result_filename}"
        api_download_url = f"{base_url}/download/{file_id}"
        
        return {
            "success": True,
            "result_id": file_id,
            "download_url": download_url,
            "api_download_url": api_download_url,
            "filename": result_filename
        }
    except Exception as e:
        logger.error("Error colorizing image: %s", str(e))
        raise HTTPException(status_code=500, detail=f"Error colorizing image: {str(e)}")

@app.get("/download/{file_id}")
async def download_result(
    file_id: str,
    verified: bool = Depends(verify_app_check)
):
    """
    Download the colorized image by file ID
    """
    result_filepath = RESULT_DIR / f"{file_id}.jpg"
    
    if not result_filepath.exists():
        raise HTTPException(status_code=404, detail="Result not found")
    
    return FileResponse(
        result_filepath,
        media_type="image/jpeg",
        filename=f"colorized_{file_id}.jpg"
    )

@app.get("/results/{filename}")
async def get_result_file(filename: str):
    """
    Serve result files directly (public endpoint for browser access)
    """
    result_filepath = RESULT_DIR / filename
    
    if not result_filepath.exists():
        raise HTTPException(status_code=404, detail="File not found")
    
    return FileResponse(
        result_filepath,
        media_type="image/jpeg"
    )

@app.get("/uploads/{filename}")
async def get_upload_file(filename: str):
    """
    Serve uploaded files directly
    """
    upload_filepath = UPLOAD_DIR / filename
    
    if not upload_filepath.exists():
        raise HTTPException(status_code=404, detail="File not found")
    
    return FileResponse(
        upload_filepath,
        media_type="image/jpeg"
    )

if __name__ == "__main__":
    import uvicorn
    port = int(os.getenv("PORT", "7860"))
    uvicorn.run(app, host="0.0.0.0", port=port)