arij155 commited on
Commit
12017de
·
verified ·
1 Parent(s): 8b39826

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +33 -22
main.py CHANGED
@@ -3,20 +3,16 @@ import numpy as np
3
  import requests
4
  import torch
5
  import firebase_admin
 
6
  from fastapi import FastAPI, BackgroundTasks
7
  from pydantic import BaseModel
8
  from ultralytics import YOLO
9
  from firebase_admin import credentials, firestore
10
- import os
11
 
12
  # --- 0. HUGGING FACE ENVIRONMENT SETUP ---
13
  os.environ['TORCH_HOME'] = '/tmp/torch_cache'
14
  os.environ['YOLO_CONFIG_DIR'] = '/tmp/ultralytics_config'
15
 
16
- # This is the most reliable way to bypass "Aborted" prompts in 2026
17
- # It tells Torch Hub to never ask for permission
18
- torch.hub.help = lambda *args, **kwargs: None
19
-
20
  # --- 1. INITIALIZE MODELS ---
21
  app = FastAPI()
22
 
@@ -30,31 +26,48 @@ device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cp
30
  print("🚀 Starting Sahl Express Engine...")
31
 
32
  # Load YOLOv8 (2D Segmentation)
33
- yolo_model = YOLO('best.pt')
 
 
 
 
34
 
35
- # Load MiDaS (Depth Estimation) - The "Trust" fix is now built-in
36
  try:
37
- print("📥 Downloading MiDaS models (this may take a minute)...")
38
- # We use trust_repo=True here; the global bypass handles the rest
39
- midas = torch.hub.load("intel-isl/MiDaS", "MiDaS_small", trust_repo=True)
40
- midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms", trust_repo=True)
 
 
 
 
 
41
 
42
  midas.to(device)
43
  midas.eval()
 
 
 
44
  transform = midas_transforms.small_transform
 
45
  print("✅ MiDaS Loaded Successfully")
46
  except Exception as e:
47
- print(f" Error loading MiDaS: {e}")
 
 
 
 
 
48
 
49
  # --- 2. FIREBASE SETUP ---
50
- # CRITICAL: Ensure 'serviceAccount.json' is uploaded to your Space!
51
  try:
52
  cred = credentials.Certificate("serviceAccount.json")
53
  firebase_admin.initialize_app(cred)
54
  db = firestore.client()
55
  print("✅ Firebase Connected")
56
  except Exception as e:
57
- print(f"⚠️ Firebase Warning: {e} (App will run but won't save data)")
58
 
59
  # Tunisian Reference Constants (cm)
60
  REFERENCE_SIZES = {
@@ -93,7 +106,7 @@ def perform_3d_measurement(image_url: str, delivery_id: str):
93
  pkg_mask = None
94
  pkg_w_px, pkg_h_px = None, None
95
 
96
- # 1. Find Ruler (Card/Coin)
97
  for i, box in enumerate(yolo_results.boxes):
98
  label = yolo_results.names[int(box.cls[0])]
99
  if label in REFERENCE_SIZES:
@@ -101,7 +114,7 @@ def perform_3d_measurement(image_url: str, delivery_id: str):
101
  pixel_cm_ratio = (x2 - x1) / REFERENCE_SIZES[label]
102
  break
103
 
104
- # 2. Find Package
105
  for i, box in enumerate(yolo_results.boxes):
106
  label = yolo_results.names[int(box.cls[0])]
107
  if label == 'package' and yolo_results.masks is not None:
@@ -111,7 +124,7 @@ def perform_3d_measurement(image_url: str, delivery_id: str):
111
  pkg_w_px, pkg_h_px = w, h
112
  break
113
 
114
- # 3. Calculate 3D Dimensions
115
  if pixel_cm_ratio and pkg_w_px is not None:
116
  mask_img = np.zeros(depth_map.shape, dtype=np.uint8)
117
  cv2.fillPoly(mask_img, [pkg_mask.astype(np.int32)], 1)
@@ -121,22 +134,21 @@ def perform_3d_measurement(image_url: str, delivery_id: str):
121
  dilated = cv2.dilate(mask_img, kernel, iterations=2)
122
  ground_depth_val = np.median(depth_map[(dilated - mask_img) == 1])
123
 
124
- # Real measurements
125
  depth_delta = abs(ground_depth_val - pkg_depth_val)
126
- real_h = round((depth_delta / pixel_cm_ratio) * 0.5, 1) # Tuning: 0.5
127
  real_w = round(pkg_w_px / pixel_cm_ratio, 1)
128
  real_l = round(pkg_h_px / pixel_cm_ratio, 1)
129
 
130
  if real_h < 0.5: real_h = 1.0
131
  volume = round(real_w * real_l * real_h, 2)
132
 
133
- # 4. Save to Firebase
134
  db.collection("orders").document(delivery_id).update({
135
  "volume_cm3": volume,
136
  "dimensions": f"{real_l}x{real_w}x{real_h} cm",
137
  "status": "Measured_3D"
138
  })
139
- print(f"📦 Success: {delivery_id} | {volume} cm3")
140
 
141
  except Exception as e:
142
  print(f"❌ Measurement Error: {e}")
@@ -148,5 +160,4 @@ async def measure_endpoint(request: ImageRequest, background_tasks: BackgroundTa
148
 
149
  if __name__ == "__main__":
150
  import uvicorn
151
- # Hugging Face looks for port 7860
152
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
3
  import requests
4
  import torch
5
  import firebase_admin
6
+ import os
7
  from fastapi import FastAPI, BackgroundTasks
8
  from pydantic import BaseModel
9
  from ultralytics import YOLO
10
  from firebase_admin import credentials, firestore
 
11
 
12
  # --- 0. HUGGING FACE ENVIRONMENT SETUP ---
13
  os.environ['TORCH_HOME'] = '/tmp/torch_cache'
14
  os.environ['YOLO_CONFIG_DIR'] = '/tmp/ultralytics_config'
15
 
 
 
 
 
16
  # --- 1. INITIALIZE MODELS ---
17
  app = FastAPI()
18
 
 
26
  print("🚀 Starting Sahl Express Engine...")
27
 
28
  # Load YOLOv8 (2D Segmentation)
29
+ try:
30
+ yolo_model = YOLO('best.pt')
31
+ print("✅ YOLOv8 Loaded")
32
+ except Exception as e:
33
+ print(f"❌ YOLO Load Error: {e}")
34
 
35
+ # --- MIDAS LOADING BLOCK (Bypassing Trusted Repo Prompt) ---
36
  try:
37
+ print("📥 Loading MiDaS (Bypassing Trust Prompts)...")
38
+
39
+ # We use skip_validation=True to tell Torch to ignore the repo verification prompt
40
+ midas = torch.hub.load(
41
+ "intel-isl/MiDaS",
42
+ "MiDaS_small",
43
+ trust_repo=True,
44
+ skip_validation=True
45
+ )
46
 
47
  midas.to(device)
48
  midas.eval()
49
+
50
+ # Load transforms
51
+ midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms")
52
  transform = midas_transforms.small_transform
53
+
54
  print("✅ MiDaS Loaded Successfully")
55
  except Exception as e:
56
+ print(f"⚠️ MiDaS Load Failed: {e}")
57
+ print("🔄 Retrying with fallback method...")
58
+ # Secondary attempt if the first one fails
59
+ midas = torch.hub.load("intel-isl/MiDaS", "MiDaS_small", force_reload=True, trust_repo=True)
60
+ midas.to(device)
61
+ midas.eval()
62
 
63
  # --- 2. FIREBASE SETUP ---
 
64
  try:
65
  cred = credentials.Certificate("serviceAccount.json")
66
  firebase_admin.initialize_app(cred)
67
  db = firestore.client()
68
  print("✅ Firebase Connected")
69
  except Exception as e:
70
+ print(f"⚠️ Firebase Error: {e}")
71
 
72
  # Tunisian Reference Constants (cm)
73
  REFERENCE_SIZES = {
 
106
  pkg_mask = None
107
  pkg_w_px, pkg_h_px = None, None
108
 
109
+ # 1. Calibration (Find Ruler/ID Card)
110
  for i, box in enumerate(yolo_results.boxes):
111
  label = yolo_results.names[int(box.cls[0])]
112
  if label in REFERENCE_SIZES:
 
114
  pixel_cm_ratio = (x2 - x1) / REFERENCE_SIZES[label]
115
  break
116
 
117
+ # 2. Identification (Find Package)
118
  for i, box in enumerate(yolo_results.boxes):
119
  label = yolo_results.names[int(box.cls[0])]
120
  if label == 'package' and yolo_results.masks is not None:
 
124
  pkg_w_px, pkg_h_px = w, h
125
  break
126
 
127
+ # 3. 3D Logic
128
  if pixel_cm_ratio and pkg_w_px is not None:
129
  mask_img = np.zeros(depth_map.shape, dtype=np.uint8)
130
  cv2.fillPoly(mask_img, [pkg_mask.astype(np.int32)], 1)
 
134
  dilated = cv2.dilate(mask_img, kernel, iterations=2)
135
  ground_depth_val = np.median(depth_map[(dilated - mask_img) == 1])
136
 
 
137
  depth_delta = abs(ground_depth_val - pkg_depth_val)
138
+ real_h = round((depth_delta / pixel_cm_ratio) * 0.5, 1)
139
  real_w = round(pkg_w_px / pixel_cm_ratio, 1)
140
  real_l = round(pkg_h_px / pixel_cm_ratio, 1)
141
 
142
  if real_h < 0.5: real_h = 1.0
143
  volume = round(real_w * real_l * real_h, 2)
144
 
145
+ # Update Firebase
146
  db.collection("orders").document(delivery_id).update({
147
  "volume_cm3": volume,
148
  "dimensions": f"{real_l}x{real_w}x{real_h} cm",
149
  "status": "Measured_3D"
150
  })
151
+ print(f"📦 Success: {delivery_id} | Vol: {volume}cm3")
152
 
153
  except Exception as e:
154
  print(f"❌ Measurement Error: {e}")
 
160
 
161
  if __name__ == "__main__":
162
  import uvicorn
 
163
  uvicorn.run(app, host="0.0.0.0", port=7860)