AdarshDRC commited on
Commit
bb4210b
·
verified ·
1 Parent(s): 62e52db

Create common/utils.py

Browse files
Files changed (1) hide show
  1. src/common/utils.py +64 -0
src/common/utils.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from fastapi import Request
3
+
4
+ def get_ip(request: Request) -> str:
5
+ forwarded = request.headers.get("X-Forwarded-For")
6
+ if forwarded:
7
+ return forwarded.split(",")[0].strip()
8
+ return request.client.host if request.client else "unknown"
9
+
10
+ def is_default_key(key: str, default: str) -> bool:
11
+ if not key or not default:
12
+ return False
13
+ return key.strip() == default.strip()
14
+
15
+ def get_cloudinary_creds(url: str) -> dict:
16
+ if not url or not url.startswith("cloudinary://"):
17
+ return {}
18
+ try:
19
+ creds = url.replace("cloudinary://", "")
20
+ auth, cloud_name = creds.split("@")
21
+ api_key, api_secret = auth.split(":")
22
+ return {
23
+ "cloud_name": cloud_name,
24
+ "api_key": api_key,
25
+ "api_secret": api_secret
26
+ }
27
+ except ValueError:
28
+ return {}
29
+
30
+ def sanitize_filename(filename: str) -> str:
31
+ if not filename:
32
+ return "unnamed_file"
33
+ return re.sub(r'[^a-zA-Z0-9_\-\.]', '_', filename)
34
+
35
+ def standardize_category_name(name: str) -> str:
36
+ if not name:
37
+ return "uncategorized"
38
+ return re.sub(r'[^a-zA-Z0-9_\-]', '_', name.lower())
39
+
40
+ def to_list(vector) -> list[float]:
41
+ try:
42
+ return [float(x) for x in vector]
43
+ except TypeError:
44
+ return []
45
+
46
+ def url_to_public_id(url: str) -> str:
47
+ if not url:
48
+ return ""
49
+ try:
50
+ parts = url.split("/upload/")
51
+ if len(parts) > 1:
52
+ path = parts[1].split("/", 1)[-1]
53
+ return path.rsplit(".", 1)[0]
54
+ return ""
55
+ except Exception:
56
+ return ""
57
+
58
+ def cld_thumb_url(url: str) -> str:
59
+ if not url:
60
+ return ""
61
+ return url.replace("/upload/", "/upload/c_thumb,w_200,g_face/")
62
+
63
+ def face_ui_score(raw_score: float) -> float:
64
+ return min(100.0, max(0.0, round(raw_score * 100, 2)))