LogicGoInfotechSpaces commited on
Commit
6c4f511
·
verified ·
1 Parent(s): e91dfad

Update app/main.py

Browse files
Files changed (1) hide show
  1. app/main.py +135 -26
app/main.py CHANGED
@@ -1,40 +1,149 @@
1
- from fastapi import FastAPI, UploadFile, File
 
2
  from huggingface_hub import hf_hub_download
3
- import torch
 
 
4
  from PIL import Image
 
5
  import io
 
 
 
 
 
 
 
 
 
6
 
7
- app = FastAPI(title="GAN Image Colorization API")
 
 
 
8
 
9
- # --------------------------
10
- # Model Loading Section
11
- # --------------------------
12
  MODEL_REPO = "Hammad712/GAN-Colorization-Model"
13
  MODEL_FILENAME = "generator.pt"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- try:
16
- print("🔄 Downloading model from Hugging Face...")
17
- model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILENAME)
18
- state_dict = torch.load(model_path, map_location="cpu")
19
- print("✅ Model loaded successfully from:", model_path)
20
- except Exception as e:
21
- print("❌ Failed to load model:", e)
22
- state_dict = None
 
23
 
 
 
24
 
25
- # --------------------------
26
- # Example Endpoint
27
- # --------------------------
28
- @app.get("/")
29
- def read_root():
30
- return {"message": "GAN Colorization API is running!"}
31
 
 
 
32
 
 
 
 
 
 
 
 
 
 
 
33
  @app.post("/colorize")
34
- async def colorize_image(file: UploadFile = File(...)):
35
- # Load the uploaded image
36
- image_bytes = await file.read()
37
- img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- # For now, just return confirmation (replace with inference logic later)
40
- return {"status": "success", "filename": file.filename}
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException, Header
2
+ from fastapi.responses import FileResponse
3
  from huggingface_hub import hf_hub_download
4
+ from firebase_admin import credentials, initialize_app, app_check
5
+ import uuid
6
+ import os
7
  from PIL import Image
8
+ import torch
9
  import io
10
+ from torchvision import transforms
11
+
12
+ app = FastAPI(title="Text-Guided Image Colorization API")
13
+
14
+ # -------------------------------------------------
15
+ # 🔐 Firebase App Check Initialization
16
+ # -------------------------------------------------
17
+ cred = credentials.Certificate("firebase-key.json") # Your service account key
18
+ initialize_app(cred)
19
 
20
+ UPLOAD_DIR = "uploads"
21
+ RESULTS_DIR = "results"
22
+ os.makedirs(UPLOAD_DIR, exist_ok=True)
23
+ os.makedirs(RESULTS_DIR, exist_ok=True)
24
 
25
+ # -------------------------------------------------
26
+ # 🧠 Load ColorizeNet Model
27
+ # -------------------------------------------------
28
  MODEL_REPO = "Hammad712/GAN-Colorization-Model"
29
  MODEL_FILENAME = "generator.pt"
30
+ model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILENAME)
31
+ state_dict = torch.load(model_path, map_location="cpu")
32
+
33
+ # (Example model structure – replace with your actual ColorizeNet)
34
+ # from your_model import ColorizeNet
35
+ # model = ColorizeNet()
36
+ # model.load_state_dict(state_dict)
37
+ # model.eval()
38
+
39
+ # Dummy colorization function
40
+ def colorize_image(img: Image.Image):
41
+ transform = transforms.ToTensor()
42
+ tensor = transform(img.convert("L")).unsqueeze(0)
43
+ tensor = tensor.repeat(1, 3, 1, 1)
44
+ output_img = transforms.ToPILImage()(tensor.squeeze())
45
+ return output_img
46
+
47
+ # -------------------------------------------------
48
+ # 🩺 1. Health Check
49
+ # -------------------------------------------------
50
+ @app.get("/health")
51
+ def health_check():
52
+ return {"status": "healthy", "model_loaded": True}
53
+
54
+ # -------------------------------------------------
55
+ # ✅ Firebase App Check Token Validation
56
+ # -------------------------------------------------
57
+ def verify_app_check_token(token: str):
58
+ # In production, verify token with Firebase REST API or Admin SDK.
59
+ if not token or len(token) < 20:
60
+ raise HTTPException(status_code=401, detail="Missing or invalid Firebase App Check token")
61
+ return True
62
 
63
+ # -------------------------------------------------
64
+ # 📤 2. Upload Image
65
+ # -------------------------------------------------
66
+ @app.post("/upload")
67
+ async def upload_image(
68
+ file: UploadFile = File(...),
69
+ x_firebase_appcheck: str = Header(None)
70
+ ):
71
+ verify_app_check_token(x_firebase_appcheck)
72
 
73
+ if not file.content_type.startswith("image/"):
74
+ raise HTTPException(status_code=400, detail="Invalid file type")
75
 
76
+ image_id = str(uuid.uuid4())
77
+ filename = f"{image_id}.jpg"
78
+ path = os.path.join(UPLOAD_DIR, filename)
 
 
 
79
 
80
+ with open(path, "wb") as f:
81
+ f.write(await file.read())
82
 
83
+ return {
84
+ "success": True,
85
+ "image_id": image_id,
86
+ "image_url": f"https://logicgoinfotechspaces-text-guided-image-colorization.hf.space/uploads/{filename}",
87
+ "filename": filename
88
+ }
89
+
90
+ # -------------------------------------------------
91
+ # 🎨 3. Colorize Image
92
+ # -------------------------------------------------
93
  @app.post("/colorize")
94
+ async def colorize(
95
+ file: UploadFile = File(...),
96
+ x_firebase_appcheck: str = Header(None)
97
+ ):
98
+ verify_app_check_token(x_firebase_appcheck)
99
+
100
+ if not file.content_type.startswith("image/"):
101
+ raise HTTPException(status_code=400, detail="Invalid file type")
102
+
103
+ img = Image.open(io.BytesIO(await file.read()))
104
+ output_img = colorize_image(img)
105
+
106
+ result_id = str(uuid.uuid4())
107
+ filename = f"{result_id}.jpg"
108
+ path = os.path.join(RESULTS_DIR, filename)
109
+ output_img.save(path)
110
+
111
+ base_url = "https://logicgoinfotechspaces-text-guided-image-colorization.hf.space"
112
+ return {
113
+ "success": True,
114
+ "result_id": result_id,
115
+ "download_url": f"{base_url}/results/{filename}",
116
+ "api_download_url": f"{base_url}/download/{result_id}",
117
+ "filename": filename
118
+ }
119
+
120
+ # -------------------------------------------------
121
+ # ⬇️ 4. Download Processed Image
122
+ # -------------------------------------------------
123
+ @app.get("/download/{file_id}")
124
+ def download_result(file_id: str, x_firebase_appcheck: str = Header(None)):
125
+ verify_app_check_token(x_firebase_appcheck)
126
+ path = os.path.join(RESULTS_DIR, f"{file_id}.jpg")
127
+ if not os.path.exists(path):
128
+ raise HTTPException(status_code=404, detail="File not found")
129
+ return FileResponse(path, media_type="image/jpeg")
130
+
131
+ # -------------------------------------------------
132
+ # 🌈 5. Get Result (Public URL)
133
+ # -------------------------------------------------
134
+ @app.get("/results/{filename}")
135
+ def get_result(filename: str):
136
+ path = os.path.join(RESULTS_DIR, filename)
137
+ if not os.path.exists(path):
138
+ raise HTTPException(status_code=404, detail="File not found")
139
+ return FileResponse(path, media_type="image/jpeg")
140
 
141
+ # -------------------------------------------------
142
+ # 🖼️ 6. Get Uploaded Image (Public URL)
143
+ # -------------------------------------------------
144
+ @app.get("/uploads/{filename}")
145
+ def get_upload(filename: str):
146
+ path = os.path.join(UPLOAD_DIR, filename)
147
+ if not os.path.exists(path):
148
+ raise HTTPException(status_code=404, detail="File not found")
149
+ return FileResponse(path, media_type="image/jpeg")