File size: 13,725 Bytes
49b5e1e 6c4f511 e91dfad 963b208 60c56d7 6c4f511 963b208 49b5e1e 6c4f511 963b208 6c4f511 963b208 d8c6239 60c56d7 d8c6239 963b208 6c4f511 60c56d7 a59cff0 49b5e1e 963b208 e91dfad d8c6239 6c4f511 d8c6239 963b208 6c4f511 963b208 6c4f511 963b208 87f9058 a7ddf76 87f9058 963b208 87f9058 6c4f511 963b208 6c4f511 d8c6239 6c4f511 60c56d7 49b5e1e 0183b1e 49b5e1e 963b208 6c4f511 963b208 87f9058 963b208 49b5e1e 963b208 ab9de00 87f9058 49b5e1e 0183b1e b475327 963b208 87f9058 963b208 293fc40 963b208 b475327 87f9058 963b208 87f9058 b475327 963b208 d8c6239 87f9058 6c4f511 963b208 6c4f511 87f9058 49b5e1e 87f9058 49b5e1e 87f9058 49b5e1e 87f9058 6c4f511 963b208 e91dfad 963b208 87f9058 963b208 49b5e1e 963b208 87f9058 ab9de00 87f9058 49b5e1e 0183b1e 6c4f511 963b208 2ebd872 87f9058 2ebd872 87f9058 2ebd872 d8c6239 2ebd872 87f9058 2ebd872 49b5e1e 2ebd872 6c4f511 963b208 87f9058 963b208 87f9058 963b208 87f9058 963b208 87f9058 963b208 6c4f511 87f9058 6c4f511 87f9058 963b208 87f9058 963b208 e4599d1 963b208 6c4f511 87f9058 6c4f511 87f9058 963b208 87f9058 963b208 |
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 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 |
from fastapi import FastAPI, File, UploadFile, HTTPException, Header, Request, Form
from typing import Optional
from fastapi.responses import FileResponse
from huggingface_hub import hf_hub_download
import uuid
import os
import io
import json
from PIL import Image
import torch
from torchvision import transforms
from app.database import (
get_database,
log_api_call,
log_image_upload,
log_colorization,
log_media_click,
close_connection,
)
try:
from firebase_admin import auth as firebase_auth
except ImportError:
firebase_auth = None
# -------------------------------------------------
# π FastAPI App
# -------------------------------------------------
app = FastAPI(title="Text-Guided Image Colorization API")
# -------------------------------------------------
# π Firebase Initialization (ENV-based)
# -------------------------------------------------
try:
import firebase_admin
from firebase_admin import credentials, app_check
firebase_json = os.getenv("FIREBASE_CREDENTIALS")
if firebase_json:
print("π₯ Loading Firebase credentials from ENV...")
firebase_dict = json.loads(firebase_json)
cred = credentials.Certificate(firebase_dict)
firebase_admin.initialize_app(cred)
else:
print("β οΈ No Firebase credentials found. Firebase disabled.")
except Exception as e:
print("β Firebase initialization failed:", e)
# -------------------------------------------------
# π Directories (FIXED FOR HUGGINGFACE SPACES)
# -------------------------------------------------
UPLOAD_DIR = "/tmp/uploads"
RESULTS_DIR = "/tmp/results"
os.makedirs(UPLOAD_DIR, exist_ok=True)
os.makedirs(RESULTS_DIR, exist_ok=True)
MEDIA_CLICK_DEFAULT_CATEGORY = os.getenv("DEFAULT_CATEGORY_FALLBACK", "69368fcd2e46bd68ae1889b2")
# -------------------------------------------------
# π§ Load GAN Colorization Model
# -------------------------------------------------
MODEL_REPO = "Hammad712/GAN-Colorization-Model"
MODEL_FILENAME = "generator.pt"
print("β¬οΈ Downloading model...")
model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILENAME)
print("π¦ Loading model weights...")
state_dict = torch.load(model_path, map_location="cpu")
# NOTE: Replace with real model architecture
# from model import ColorizeNet
# model = ColorizeNet()
# model.load_state_dict(state_dict)
# model.eval()
def colorize_image(img: Image.Image):
""" Dummy colorizer (replace with real model.predict) """
transform = transforms.ToTensor()
tensor = transform(img.convert("L")).unsqueeze(0)
tensor = tensor.repeat(1, 3, 1, 1)
output_img = transforms.ToPILImage()(tensor.squeeze())
return output_img
# -------------------------------------------------
# ποΈ MongoDB Initialization
# -------------------------------------------------
@app.on_event("startup")
async def startup_event():
"""Initialize MongoDB on startup"""
try:
db = get_database()
if db is not None:
print("β
MongoDB initialized successfully!")
except Exception as e:
print(f"β οΈ MongoDB initialization failed: {e}")
@app.on_event("shutdown")
async def shutdown_event():
"""Cleanup on shutdown"""
close_connection()
print("Application shutdown")
# -------------------------------------------------
# π©Ί Health Check
# -------------------------------------------------
@app.get("/health")
def health_check(request: Request):
response = {"status": "healthy", "model_loaded": True}
# Log API call
log_api_call(
endpoint="/health",
method="GET",
status_code=200,
response_data=response,
ip_address=request.client.host if request.client else None
)
return response
# -------------------------------------------------
# π Firebase Token Validator
# -------------------------------------------------
def verify_app_check_token(token: str):
if not token or len(token) < 20:
raise HTTPException(status_code=401, detail="Invalid Firebase App Check token")
return True
def _resolve_user_id(request: Request, supplied_user_id: Optional[str]) -> Optional[str]:
"""Return supplied user_id if provided and not empty, otherwise None (will auto-generate in log_media_click)."""
if supplied_user_id and supplied_user_id.strip():
return supplied_user_id.strip()
return None
# -------------------------------------------------
# π€ Upload Image
# -------------------------------------------------
@app.post("/upload")
async def upload_image(
request: Request,
file: UploadFile = File(...),
x_firebase_appcheck: str = Header(None),
user_id: Optional[str] = Form(None),
category_id: Optional[str] = Form(None),
categoryId: Optional[str] = Form(None),
):
verify_app_check_token(x_firebase_appcheck)
ip_address = request.client.host if request.client else None
effective_user_id = _resolve_user_id(request, user_id)
effective_category_id = (category_id or categoryId) if (category_id or categoryId) else None
if effective_category_id:
effective_category_id = effective_category_id.strip() if isinstance(effective_category_id, str) else effective_category_id
if not effective_category_id:
effective_category_id = None
if not file.content_type.startswith("image/"):
log_api_call(
endpoint="/upload",
method="POST",
status_code=400,
error="Invalid file type",
ip_address=ip_address
)
raise HTTPException(status_code=400, detail="Invalid file type")
image_id = f"{uuid.uuid4()}.jpg"
file_path = os.path.join(UPLOAD_DIR, image_id)
img_bytes = await file.read()
file_size = len(img_bytes)
with open(file_path, "wb") as f:
f.write(img_bytes)
base_url = "https://logicgoinfotechspaces-text-guided-image-colorization.hf.space"
response_data = {
"success": True,
"image_id": image_id.replace(".jpg", ""),
"file_url": f"{base_url}/uploads/{image_id}"
}
# Log to MongoDB
log_image_upload(
image_id=image_id.replace(".jpg", ""),
filename=file.filename or image_id,
file_size=file_size,
content_type=file.content_type or "image/jpeg",
user_id=effective_user_id,
ip_address=ip_address
)
log_api_call(
endpoint="/upload",
method="POST",
status_code=200,
request_data={"filename": file.filename, "content_type": file.content_type},
response_data=response_data,
user_id=effective_user_id,
ip_address=ip_address
)
log_media_click(
user_id=effective_user_id,
category_id=effective_category_id,
endpoint_path=str(request.url.path),
default_category_id=MEDIA_CLICK_DEFAULT_CATEGORY,
)
return response_data
# -------------------------------------------------
# π¨ Colorize Image
# -------------------------------------------------
@app.post("/colorize")
async def colorize(
request: Request,
file: UploadFile = File(...),
x_firebase_appcheck: str = Header(None),
user_id: Optional[str] = Form(None),
category_id: Optional[str] = Form(None),
categoryId: Optional[str] = Form(None),
):
import time
start_time = time.time()
verify_app_check_token(x_firebase_appcheck)
ip_address = request.client.host if request.client else None
effective_user_id = _resolve_user_id(request, user_id)
effective_category_id = (category_id or categoryId) if (category_id or categoryId) else None
if effective_category_id:
effective_category_id = effective_category_id.strip() if isinstance(effective_category_id, str) else effective_category_id
if not effective_category_id:
effective_category_id = None
if not file.content_type.startswith("image/"):
error_msg = "Invalid file type"
log_api_call(
endpoint="/colorize",
method="POST",
status_code=400,
error=error_msg,
ip_address=ip_address
)
# Log failed colorization
log_colorization(
result_id=None,
model_type="gan",
processing_time=None,
user_id=effective_user_id,
ip_address=ip_address,
status="failed",
error=error_msg
)
raise HTTPException(status_code=400, detail=error_msg)
try:
img = Image.open(io.BytesIO(await file.read()))
output_img = colorize_image(img)
processing_time = time.time() - start_time
result_id = f"{uuid.uuid4()}.jpg"
output_path = os.path.join(RESULTS_DIR, result_id)
output_img.save(output_path)
base_url = "https://logicgoinfotechspaces-text-guided-image-colorization.hf.space"
result_id_clean = result_id.replace(".jpg", "")
response_data = {
"success": True,
"result_id": result_id_clean,
"download_url": f"{base_url}/results/{result_id}",
"api_download": f"{base_url}/download/{result_id_clean}"
}
# Log to MongoDB (colorization_db -> colorizations)
log_colorization(
result_id=result_id_clean,
model_type="gan",
processing_time=processing_time,
user_id=effective_user_id,
ip_address=ip_address,
status="success"
)
log_api_call(
endpoint="/colorize",
method="POST",
status_code=200,
request_data={"filename": file.filename, "content_type": file.content_type},
response_data=response_data,
user_id=effective_user_id,
ip_address=ip_address
)
log_media_click(
user_id=effective_user_id,
category_id=effective_category_id,
endpoint_path=str(request.url.path),
default_category_id=MEDIA_CLICK_DEFAULT_CATEGORY,
)
return response_data
except Exception as e:
error_msg = str(e)
logger.error("Error colorizing image: %s", error_msg)
# Log failed colorization to colorizations collection
log_colorization(
result_id=None,
model_type="gan",
processing_time=None,
user_id=effective_user_id,
ip_address=ip_address,
status="failed",
error=error_msg
)
log_api_call(
endpoint="/colorize",
method="POST",
status_code=500,
error=error_msg,
user_id=effective_user_id,
ip_address=ip_address
)
raise HTTPException(status_code=500, detail=f"Error colorizing image: {error_msg}")
# -------------------------------------------------
# β¬οΈ Download via API (Secure)
# -------------------------------------------------
@app.get("/download/{file_id}")
def download_result(
request: Request,
file_id: str,
x_firebase_appcheck: str = Header(None)
):
verify_app_check_token(x_firebase_appcheck)
ip_address = request.client.host if request.client else None
filename = f"{file_id}.jpg"
path = os.path.join(RESULTS_DIR, filename)
if not os.path.exists(path):
log_api_call(
endpoint=f"/download/{file_id}",
method="GET",
status_code=404,
error="Result not found",
ip_address=ip_address
)
raise HTTPException(status_code=404, detail="Result not found")
log_api_call(
endpoint=f"/download/{file_id}",
method="GET",
status_code=200,
request_data={"file_id": file_id},
ip_address=ip_address
)
return FileResponse(path, media_type="image/jpeg")
# -------------------------------------------------
# π Public Result File
# -------------------------------------------------
@app.get("/results/{filename}")
def get_result(request: Request, filename: str):
ip_address = request.client.host if request.client else None
path = os.path.join(RESULTS_DIR, filename)
if not os.path.exists(path):
log_api_call(
endpoint=f"/results/{filename}",
method="GET",
status_code=404,
error="Result not found",
ip_address=ip_address
)
raise HTTPException(status_code=404, detail="Result not found")
log_api_call(
endpoint=f"/results/{filename}",
method="GET",
status_code=200,
request_data={"filename": filename},
ip_address=ip_address
)
return FileResponse(path, media_type="image/jpeg")
# -------------------------------------------------
# π Public Uploaded File
# -------------------------------------------------
@app.get("/uploads/{filename}")
def get_upload(request: Request, filename: str):
ip_address = request.client.host if request.client else None
path = os.path.join(UPLOAD_DIR, filename)
if not os.path.exists(path):
log_api_call(
endpoint=f"/uploads/{filename}",
method="GET",
status_code=404,
error="File not found",
ip_address=ip_address
)
raise HTTPException(status_code=404, detail="File not found")
log_api_call(
endpoint=f"/uploads/{filename}",
method="GET",
status_code=200,
request_data={"filename": filename},
ip_address=ip_address
)
return FileResponse(path, media_type="image/jpeg")
|