File size: 5,981 Bytes
6c4f511
 
e91dfad
963b208
 
 
 
60c56d7
6c4f511
963b208
6c4f511
963b208
 
 
 
6c4f511
963b208
 
 
d8c6239
 
 
 
 
 
 
 
 
 
 
 
 
60c56d7
d8c6239
 
 
963b208
 
 
 
 
6c4f511
 
60c56d7
963b208
 
 
e91dfad
 
d8c6239
 
6c4f511
d8c6239
963b208
6c4f511
 
963b208
 
 
 
 
6c4f511
 
963b208
 
 
 
 
 
 
 
 
 
 
 
 
6c4f511
963b208
 
 
6c4f511
 
d8c6239
6c4f511
60c56d7
963b208
 
 
6c4f511
963b208
 
 
 
ab9de00
b475327
963b208
 
 
293fc40
963b208
b475327
963b208
6c4f511
b475327
963b208
d8c6239
6c4f511
 
963b208
 
6c4f511
 
963b208
 
 
e91dfad
963b208
 
 
 
ab9de00
6c4f511
963b208
 
 
6c4f511
 
 
293fc40
963b208
 
6c4f511
963b208
d8c6239
6c4f511
 
963b208
 
 
6c4f511
 
963b208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c4f511
 
 
 
963b208
 
e4599d1
963b208
 
 
6c4f511
 
 
 
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
from fastapi import FastAPI, File, UploadFile, HTTPException, Header
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

# -------------------------------------------------
# πŸš€ 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)

# -------------------------------------------------
# 🧠 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

# -------------------------------------------------
# 🩺 Health Check
# -------------------------------------------------
@app.get("/health")
def health_check():
    return {"status": "healthy", "model_loaded": True}

# -------------------------------------------------
# πŸ” 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

# -------------------------------------------------
# πŸ“€ Upload Image
# -------------------------------------------------
@app.post("/upload")
async def upload_image(
    file: UploadFile = File(...),
    x_firebase_appcheck: str = Header(None)
):
    verify_app_check_token(x_firebase_appcheck)

    if not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="Invalid file type")

    image_id = f"{uuid.uuid4()}.jpg"
    file_path = os.path.join(UPLOAD_DIR, image_id)

    with open(file_path, "wb") as f:
        f.write(await file.read())

    base_url = "https://logicgoinfotechspaces-text-guided-image-colorization.hf.space"

    return {
        "success": True,
        "image_id": image_id.replace(".jpg", ""),
        "file_url": f"{base_url}/uploads/{image_id}"
    }

# -------------------------------------------------
# 🎨 Colorize Image
# -------------------------------------------------
@app.post("/colorize")
async def colorize(
    file: UploadFile = File(...),
    x_firebase_appcheck: str = Header(None)
):
    verify_app_check_token(x_firebase_appcheck)

    if not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="Invalid file type")

    img = Image.open(io.BytesIO(await file.read()))
    output_img = colorize_image(img)

    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"

    return {
        "success": True,
        "result_id": result_id.replace(".jpg", ""),
        "download_url": f"{base_url}/results/{result_id}",
        "api_download": f"{base_url}/download/{result_id.replace('.jpg','')}"
    }

# -------------------------------------------------
# ⬇️ Download via API (Secure)
# -------------------------------------------------
@app.get("/download/{file_id}")
def download_result(file_id: str, x_firebase_appcheck: str = Header(None)):
    verify_app_check_token(x_firebase_appcheck)

    filename = f"{file_id}.jpg"
    path = os.path.join(RESULTS_DIR, filename)

    if not os.path.exists(path):
        raise HTTPException(status_code=404, detail="Result not found")

    return FileResponse(path, media_type="image/jpeg")

# -------------------------------------------------
# 🌐 Public Result File
# -------------------------------------------------
@app.get("/results/{filename}")
def get_result(filename: str):
    path = os.path.join(RESULTS_DIR, filename)
    if not os.path.exists(path):
        raise HTTPException(status_code=404, detail="Result not found")
    return FileResponse(path, media_type="image/jpeg")

# -------------------------------------------------
# 🌐 Public Uploaded File
# -------------------------------------------------
@app.get("/uploads/{filename}")
def get_upload(filename: str):
    path = os.path.join(UPLOAD_DIR, filename)
    if not os.path.exists(path):
        raise HTTPException(status_code=404, detail="File not found")
    return FileResponse(path, media_type="image/jpeg")