bhavinmatariya commited on
Commit
210ffdf
·
1 Parent(s): 19ac182

Refactor skin_analysis endpoint to use RapidAPI for skin analysis

Browse files
Files changed (1) hide show
  1. app.py +62 -106
app.py CHANGED
@@ -5,6 +5,9 @@ import os
5
  import tempfile
6
  import json
7
  import requests
 
 
 
8
 
9
  # Import deepface with error handling
10
  try:
@@ -174,126 +177,79 @@ async def analyze_image(file: UploadFile = File(...)):
174
  pass
175
 
176
 
177
- # @app.post("/skin-analysis")
178
- # async def skin_analysis(file: UploadFile = File(...)):
179
- # """
180
- # Upload an image and get comprehensive skin analysis results.
181
 
182
- # Args:
183
- # file: Image file to analyze (supports common image formats)
184
 
185
- # Returns:
186
- # JSON response with detailed skin analysis information
187
- # """
188
- # # Validate file type
189
- # if not file.content_type or not file.content_type.startswith('image/'):
190
- # raise HTTPException(status_code=400, detail="File must be an image")
191
 
192
- # # Get API key from environment variable
193
- # api_key = os.getenv("AILABAPI_API_KEY", "")
 
 
 
 
 
194
 
195
- # # Create a temporary file to save the uploaded image
196
- # tmp_file_path = None
197
- # try:
198
- # # Read file contents
199
- # contents = await file.read()
200
 
201
- # # Create temporary file and write contents
202
- # with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as tmp_file:
203
- # tmp_file.write(contents)
204
- # tmp_file_path = tmp_file.name
205
 
206
- # # Prepare request to ailabapi
207
- # url = "https://www.ailabapi.com/api/portrait/analysis/skin-analysis"
208
 
209
- # # Open the temporary file for the request
210
- # with open(tmp_file_path, 'rb') as image_file:
211
- # files = {"image": (file.filename or "image.jpg", image_file, file.content_type)}
212
- # headers = {"ailabapi-api-key": api_key}
213
-
214
- # # Make request to ailabapi
215
- # response = requests.post(url, files=files, headers=headers)
216
-
217
- # if response.status_code != 200:
218
- # raise HTTPException(
219
- # status_code=response.status_code,
220
- # detail=f"External API error: {response.text}"
221
- # )
222
-
223
- # data = response.json()
224
 
225
- # # Mapping dictionaries
226
- # yes_no_mapping = {0: "No", 1: "Yes"}
227
- # eyelids_mapping = {
228
- # 0: "Single eyelids",
229
- # 1: "Parallel Double Eyelids",
230
- # 2: "Scalloped Double Eyelids"
231
- # }
232
- # skin_type_mapping = {
233
- # 0: "Oily skin",
234
- # 1: "Dry skin",
235
- # 2: "Neutral skin",
236
- # 3: "Combination skin"
237
- # }
238
 
239
- # # Fields that use Yes/No mapping
240
- # yes_no_fields = [
241
- # "pores_left_cheek", "nasolabial_fold", "eye_pouch", "forehead_wrinkle",
242
- # "skin_spot", "acne", "pores_forehead", "pores_jaw", "eye_finelines",
243
- # "dark_circle", "crows_feet", "pores_right_cheek", "blackhead",
244
- # "glabella_wrinkle", "mole"
245
- # ]
246
 
247
- # # Transform the result data
248
- # if "result" in data:
249
- # result = data["result"]
250
-
251
- # # Transform Yes/No fields
252
- # for field in yes_no_fields:
253
- # if field in result and "value" in result[field]:
254
- # result[field]["value_label"] = yes_no_mapping.get(result[field]["value"], "Unknown")
255
-
256
- # # Transform eyelid fields
257
- # if "left_eyelids" in result and "value" in result["left_eyelids"]:
258
- # result["left_eyelids"]["value_label"] = eyelids_mapping.get(result["left_eyelids"]["value"], "Unknown")
259
-
260
- # if "right_eyelids" in result and "value" in result["right_eyelids"]:
261
- # result["right_eyelids"]["value_label"] = eyelids_mapping.get(result["right_eyelids"]["value"], "Unknown")
262
-
263
- # # Transform skin_type
264
- # if "skin_type" in result:
265
- # if "skin_type" in result["skin_type"]:
266
- # result["skin_type"]["skin_type_label"] = skin_type_mapping.get(result["skin_type"]["skin_type"], "Unknown")
267
- # if "details" in result["skin_type"]:
268
- # for detail in result["skin_type"]["details"]:
269
- # if "value" in detail:
270
- # detail["value_label"] = skin_type_mapping.get(detail["value"], "Unknown")
271
 
272
- # return JSONResponse(content=data)
 
273
 
274
- # except requests.exceptions.RequestException as e:
275
- # raise HTTPException(
276
- # status_code=500,
277
- # detail=f"Error calling external API: {str(e)}"
278
- # )
279
- # except Exception as e:
280
- # raise HTTPException(
281
- # status_code=500,
282
- # detail=f"Error processing image: {str(e)}"
283
- # )
284
- # finally:
285
- # # Clean up temporary file
286
- # if tmp_file_path and os.path.exists(tmp_file_path):
287
- # try:
288
- # import time
289
- # time.sleep(0.1)
290
- # os.unlink(tmp_file_path)
291
- # except (PermissionError, OSError):
292
- # pass
293
 
294
 
295
  @app.get("/health")
296
  async def health_check():
297
  """Health check endpoint"""
298
- return {"status": "healthy"}
299
-
 
5
  import tempfile
6
  import json
7
  import requests
8
+ from io import BytesIO
9
+ from dotenv import load_dotenv
10
+ load_dotenv()
11
 
12
  # Import deepface with error handling
13
  try:
 
177
  pass
178
 
179
 
180
+ @app.post("/skin-analysis")
181
+ async def skin_analysis(file: UploadFile = File(...)):
182
+ """
183
+ Upload an image and get comprehensive skin analysis results.
184
 
185
+ Args:
186
+ file: Image file to analyze (supports common image formats)
187
 
188
+ Returns:
189
+ JSON response with detailed skin analysis information
190
+ """
191
+ # Validate file type
192
+ if not file.content_type or not file.content_type.startswith('image/'):
193
+ raise HTTPException(status_code=400, detail="File must be an image")
194
 
195
+ # Get API key from environment variable
196
+ api_key = os.getenv("RAPIDAPI_KEY", "")
197
+ if not api_key:
198
+ raise HTTPException(
199
+ status_code=500,
200
+ detail="RAPIDAPI_KEY environment variable is not set"
201
+ )
202
 
203
+ try:
204
+ # Read file contents
205
+ contents = await file.read()
 
 
206
 
207
+ # Prepare request to RapidAPI
208
+ url = "https://skin-analysis-api.p.rapidapi.com/predict"
209
+ querystring = {"lang": "en"}
 
210
 
211
+ # Use BytesIO to create a file-like object from the contents
212
+ file_obj = BytesIO(contents)
213
 
214
+ # Try "file" as field name first (common for RapidAPI endpoints)
215
+ files = {"file": (file.filename or "image.jpg", file_obj, file.content_type)}
216
+ headers = {
217
+ "x-rapidapi-key": api_key,
218
+ "x-rapidapi-host": "skin-analysis-api.p.rapidapi.com"
219
+ }
 
 
 
 
 
 
 
 
 
220
 
221
+ # Make request to RapidAPI
222
+ # Note: When using files parameter, requests automatically sets Content-Type to multipart/form-data
223
+ response = requests.post(url, files=files, headers=headers, params=querystring)
 
 
 
 
 
 
 
 
 
 
224
 
225
+ # If "file" doesn't work, try "image" as fallback
226
+ if response.status_code == 400 and "No file found" in response.text:
227
+ file_obj.seek(0) # Reset file pointer
228
+ files = {"image": (file.filename or "image.jpg", file_obj, file.content_type)}
229
+ response = requests.post(url, files=files, headers=headers, params=querystring)
 
 
230
 
231
+ if response.status_code != 200:
232
+ raise HTTPException(
233
+ status_code=response.status_code,
234
+ detail=f"External API error: {response.text}"
235
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
+ data = response.json()
238
+ return JSONResponse(content=data)
239
 
240
+ except requests.exceptions.RequestException as e:
241
+ raise HTTPException(
242
+ status_code=500,
243
+ detail=f"Error calling external API: {str(e)}"
244
+ )
245
+ except Exception as e:
246
+ raise HTTPException(
247
+ status_code=500,
248
+ detail=f"Error processing image: {str(e)}"
249
+ )
 
 
 
 
 
 
 
 
 
250
 
251
 
252
  @app.get("/health")
253
  async def health_check():
254
  """Health check endpoint"""
255
+ return {"status": "healthy"}