LogicGoInfotechSpaces commited on
Commit
fe052a3
·
verified ·
1 Parent(s): dfe9b3f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -52
app.py CHANGED
@@ -45,8 +45,11 @@ hf_client = InferenceClient(token=HF_TOKEN)
45
  # ---------------------------------------------------------------------
46
  # MongoDB setup
47
  # ---------------------------------------------------------------------
48
- MONGODB_URI = "mongodb+srv://harilogicgo_db_user:EpWocJKRpXau8eBW@images.nh9bx9l.mongodb.net/?appName=images"
49
- DB_NAME = "polaroid_db"
 
 
 
50
 
51
  mongo = MongoClient(MONGODB_URI)
52
  db = mongo[DB_NAME]
@@ -69,7 +72,7 @@ app.add_middleware(
69
  # Auth dependency
70
  # ---------------------------------------------------------------------
71
  async def verify_firebase_token(request: Request):
72
- """Middleware-like dependency to verify Firebase JWT from Authorization header."""
73
  auth_header = request.headers.get("Authorization")
74
  if not auth_header or not auth_header.startswith("Bearer "):
75
  raise HTTPException(status_code=401, detail="Missing or invalid Authorization header")
@@ -96,8 +99,11 @@ class HealthResponse(BaseModel):
96
  @app.get("/health", response_model=HealthResponse)
97
  def health():
98
  """Public health check"""
99
- mongo.admin.command("ping")
100
- return HealthResponse(status="ok", db=db.name, model="Qwen/Qwen-Image-Edit")
 
 
 
101
 
102
 
103
  @app.post("/generate")
@@ -108,70 +114,77 @@ async def generate(
108
  user=Depends(verify_firebase_token)
109
  ):
110
  """Generate edited image using HF Inference (secured by Firebase Auth) and log only response time."""
111
- start_time = datetime.utcnow() # Start time for response time logging
 
112
  try:
 
113
  img1_bytes = await image1.read()
114
  pil_img1 = Image.open(io.BytesIO(img1_bytes)).convert("RGB")
115
- except Exception as e:
116
- raise HTTPException(status_code=400, detail=f"Failed to read first image: {e}")
117
 
118
- pil_img2 = None
119
- img2_bytes = None
120
- if image2:
121
- try:
122
  img2_bytes = await image2.read()
123
  pil_img2 = Image.open(io.BytesIO(img2_bytes)).convert("RGB")
124
- except Exception as e:
125
- raise HTTPException(status_code=400, detail=f"Failed to read second image: {e}")
126
-
127
- if pil_img2:
128
- total_width = pil_img1.width + pil_img2.width
129
- max_height = max(pil_img1.height, pil_img2.height)
130
- combined_img = Image.new("RGB", (total_width, max_height))
131
- combined_img.paste(pil_img1, (0, 0))
132
- combined_img.paste(pil_img2, (pil_img1.width, 0))
133
- else:
134
- combined_img = pil_img1
135
 
136
- try:
 
 
 
 
 
 
 
 
 
 
137
  pil_output = hf_client.image_to_image(
138
  image=combined_img,
139
  prompt=prompt,
140
  model="Qwen/Qwen-Image-Edit"
141
  )
 
142
  out_buf = io.BytesIO()
143
  pil_output.save(out_buf, format="PNG")
144
  out_bytes = out_buf.getvalue()
145
- except Exception as e:
146
- traceback.print_exc()
147
- raise HTTPException(status_code=500, detail=f"Inference failed: {e}")
148
-
149
- out_id = fs.put(
150
- out_bytes,
151
- filename=f"result_{datetime.utcnow().timestamp()}.png",
152
- contentType="image/png",
153
- role="output",
154
- user_email=user.get("email"),
155
- )
156
 
157
- # Calculate response time in milliseconds
158
- response_time_ms = (datetime.utcnow() - start_time).total_seconds() * 1000
 
 
 
 
 
159
 
160
- # Log only response time
161
- try:
162
- logs_collection.insert_one({
163
- "timestamp": datetime.utcnow(),
164
- "user": user.get("email"),
165
- "response_time_ms": response_time_ms
166
- })
167
- except Exception as e:
168
- print("⚠️ Failed to log response time:", e)
 
 
 
 
 
 
169
 
170
- return JSONResponse({
171
- "output_image_id": str(out_id),
172
- "user": user.get("email"),
173
- "response_time_ms": response_time_ms
174
- })
 
 
 
 
 
 
 
 
175
 
176
 
177
  @app.get("/image/{image_id}")
@@ -196,7 +209,6 @@ def get_image(image_id: str, download: Optional[bool] = False):
196
  headers=headers
197
  )
198
 
199
-
200
  # ---------------------------------------------------------------------
201
  # Run locally
202
  # ---------------------------------------------------------------------
 
45
  # ---------------------------------------------------------------------
46
  # MongoDB setup
47
  # ---------------------------------------------------------------------
48
+ MONGODB_URI = os.getenv("MONGODB_URI")
49
+ if not MONGODB_URI:
50
+ raise RuntimeError("MONGODB_URI not set in environment variables")
51
+
52
+ DB_NAME = os.getenv("DB_NAME", "polaroid_db")
53
 
54
  mongo = MongoClient(MONGODB_URI)
55
  db = mongo[DB_NAME]
 
72
  # Auth dependency
73
  # ---------------------------------------------------------------------
74
  async def verify_firebase_token(request: Request):
75
+ """Verify Firebase JWT from Authorization header"""
76
  auth_header = request.headers.get("Authorization")
77
  if not auth_header or not auth_header.startswith("Bearer "):
78
  raise HTTPException(status_code=401, detail="Missing or invalid Authorization header")
 
99
  @app.get("/health", response_model=HealthResponse)
100
  def health():
101
  """Public health check"""
102
+ try:
103
+ mongo.admin.command("ping")
104
+ return HealthResponse(status="ok", db=db.name, model="Qwen/Qwen-Image-Edit")
105
+ except Exception as e:
106
+ raise HTTPException(status_code=500, detail=f"DB ping failed: {e}")
107
 
108
 
109
  @app.post("/generate")
 
114
  user=Depends(verify_firebase_token)
115
  ):
116
  """Generate edited image using HF Inference (secured by Firebase Auth) and log only response time."""
117
+ start_time = datetime.utcnow() # Start timer
118
+
119
  try:
120
+ # Read first image
121
  img1_bytes = await image1.read()
122
  pil_img1 = Image.open(io.BytesIO(img1_bytes)).convert("RGB")
 
 
123
 
124
+ pil_img2 = None
125
+ img2_bytes = None
126
+ if image2:
 
127
  img2_bytes = await image2.read()
128
  pil_img2 = Image.open(io.BytesIO(img2_bytes)).convert("RGB")
 
 
 
 
 
 
 
 
 
 
 
129
 
130
+ # Combine images if two provided
131
+ if pil_img2:
132
+ total_width = pil_img1.width + pil_img2.width
133
+ max_height = max(pil_img1.height, pil_img2.height)
134
+ combined_img = Image.new("RGB", (total_width, max_height))
135
+ combined_img.paste(pil_img1, (0, 0))
136
+ combined_img.paste(pil_img2, (pil_img1.width, 0))
137
+ else:
138
+ combined_img = pil_img1
139
+
140
+ # Run HF inference
141
  pil_output = hf_client.image_to_image(
142
  image=combined_img,
143
  prompt=prompt,
144
  model="Qwen/Qwen-Image-Edit"
145
  )
146
+
147
  out_buf = io.BytesIO()
148
  pil_output.save(out_buf, format="PNG")
149
  out_bytes = out_buf.getvalue()
 
 
 
 
 
 
 
 
 
 
 
150
 
151
+ # Save output to GridFS
152
+ out_id = fs.put(
153
+ out_bytes,
154
+ filename=f"result_{datetime.utcnow().timestamp()}.png",
155
+ contentType="image/png",
156
+ user_email=user.get("email"),
157
+ )
158
 
159
+ # Calculate response time
160
+ end_time = datetime.utcnow()
161
+ response_time_ms = (end_time - start_time).total_seconds() * 1000
162
+
163
+ # Log response time only
164
+ try:
165
+ logs_collection.insert_one({
166
+ "timestamp": end_time,
167
+ "user": user.get("email"),
168
+ "response_time_ms": response_time_ms
169
+ })
170
+ except Exception as e:
171
+ print("⚠️ Failed to log response time:", e)
172
+
173
+ return JSONResponse({"output_image_id": str(out_id), "user": user.get("email")})
174
 
175
+ except Exception as e:
176
+ traceback.print_exc()
177
+ end_time = datetime.utcnow()
178
+ response_time_ms = (end_time - start_time).total_seconds() * 1000
179
+ try:
180
+ logs_collection.insert_one({
181
+ "timestamp": end_time,
182
+ "user": user.get("email") if user else "unknown",
183
+ "response_time_ms": response_time_ms
184
+ })
185
+ except Exception:
186
+ pass
187
+ raise HTTPException(status_code=500, detail=f"Processing failed: {e}")
188
 
189
 
190
  @app.get("/image/{image_id}")
 
209
  headers=headers
210
  )
211
 
 
212
  # ---------------------------------------------------------------------
213
  # Run locally
214
  # ---------------------------------------------------------------------