aniketkumar1106 commited on
Commit
fd44eb0
·
verified ·
1 Parent(s): 4171a3d

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +22 -31
server.py CHANGED
@@ -27,43 +27,38 @@ DB_TARGET = "orbiitt.db"
27
 
28
  def setup_environment():
29
  token = os.environ.get("HF_TOKEN")
30
- if not os.path.exists(IMAGE_DIR):
31
- os.makedirs(IMAGE_DIR)
 
32
 
33
  try:
34
- logger.info(f"Syncing from {DATASET_REPO}...")
35
  snapshot_download(repo_id=DATASET_REPO, repo_type="dataset", token=token, local_dir=".")
36
 
37
- zip_name = "orbiitt_db.zip"
38
- if os.path.exists(zip_name):
39
- with zipfile.ZipFile(zip_name, 'r') as z:
40
  z.extractall("temp_extract")
41
 
42
  for root, _, files in os.walk("temp_extract"):
43
  for f in files:
44
  src = os.path.join(root, f)
45
-
46
- # 1. DATABASE FIX: Force rename to 'orbiitt.db'
47
- if f in ["orbiitt_db", "orbiitt_db.db", "orbiitt.db"] or f.endswith(".db"):
48
- if not os.path.exists(DB_TARGET):
49
- shutil.move(src, f"./{DB_TARGET}")
50
- logger.info(f"DB Found: {f}")
51
-
52
- # 2. IMAGE FIX: Remove spaces and %20 from filenames
53
  elif f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
54
- # Unquote removes %20, replace(' ', '_') removes spaces
55
- clean_name = urllib.parse.unquote(f).replace(" ", "_")
56
  dest = os.path.join(IMAGE_DIR, clean_name)
57
- shutil.move(src, dest)
58
-
59
  shutil.rmtree("temp_extract")
60
 
61
- # Cleanup: Rename any files left in root that should be DB
62
  if os.path.exists("orbiitt_db") and not os.path.exists(DB_TARGET):
63
  shutil.move("orbiitt_db", DB_TARGET)
64
 
 
65
  except Exception as e:
66
- logger.error(f"Setup Error: {e}")
67
 
68
  setup_environment()
69
 
@@ -74,23 +69,18 @@ try:
74
  from orbiitt_engine import OrbiittEngine
75
  if os.path.exists(DB_TARGET):
76
  engine = OrbiittEngine()
77
- logger.info("ENGINE ONLINE")
78
  except Exception as e:
79
  logger.error(f"ENGINE ERROR: {e}")
80
 
81
  @app.get("/")
82
  def health():
83
  imgs = os.listdir(IMAGE_DIR) if os.path.exists(IMAGE_DIR) else []
84
- return {
85
- "engine": engine is not None,
86
- "db": os.path.exists(DB_TARGET),
87
- "img_count": len(imgs),
88
- "first_img": imgs[0] if imgs else None
89
- }
90
 
91
  @app.post("/search")
92
  async def search(text: str = Form(None), weight: float = Form(0.5), file: UploadFile = File(None)):
93
- if not engine: raise HTTPException(503, detail="Engine Offline")
94
  t_path = None
95
  try:
96
  if file:
@@ -99,10 +89,11 @@ async def search(text: str = Form(None), weight: float = Form(0.5), file: Upload
99
 
100
  results = engine.search(text_query=text, image_file=t_path, text_weight=weight)
101
 
102
- # 3. FIX RESULT PATHS: Ensure the frontend gets the "Clean" names
103
  for r in results:
104
- if 'url' in r:
105
- r['url'] = r['url'].replace(" ", "_")
 
106
 
107
  return {"results": results}
108
  except Exception as e:
 
27
 
28
  def setup_environment():
29
  token = os.environ.get("HF_TOKEN")
30
+ # Clean old data to prevent version mismatch
31
+ if os.path.exists(IMAGE_DIR): shutil.rmtree(IMAGE_DIR)
32
+ os.makedirs(IMAGE_DIR)
33
 
34
  try:
35
+ logger.info(f"Downloading dataset from {DATASET_REPO}...")
36
  snapshot_download(repo_id=DATASET_REPO, repo_type="dataset", token=token, local_dir=".")
37
 
38
+ if os.path.exists("orbiitt_db.zip"):
39
+ with zipfile.ZipFile("orbiitt_db.zip", 'r') as z:
 
40
  z.extractall("temp_extract")
41
 
42
  for root, _, files in os.walk("temp_extract"):
43
  for f in files:
44
  src = os.path.join(root, f)
45
+ # 1. DB LOCATOR: Handles nested or renamed DB files
46
+ if f.lower() in ["orbiitt_db", "orbiitt.db"] or (f.endswith(".db") and not f.startswith(".")):
47
+ shutil.copy(src, f"./{DB_TARGET}")
48
+ # 2. IMAGE NORMALIZER: Fixes encoding and moves to static folder
 
 
 
 
49
  elif f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
50
+ clean_name = urllib.parse.unquote(f)
 
51
  dest = os.path.join(IMAGE_DIR, clean_name)
52
+ shutil.copy(src, dest)
 
53
  shutil.rmtree("temp_extract")
54
 
55
+ # Root fallback for database
56
  if os.path.exists("orbiitt_db") and not os.path.exists(DB_TARGET):
57
  shutil.move("orbiitt_db", DB_TARGET)
58
 
59
+ logger.info(f"READY: Images={len(os.listdir(IMAGE_DIR))} DB={os.path.exists(DB_TARGET)}")
60
  except Exception as e:
61
+ logger.error(f"FATAL SETUP ERROR: {e}")
62
 
63
  setup_environment()
64
 
 
69
  from orbiitt_engine import OrbiittEngine
70
  if os.path.exists(DB_TARGET):
71
  engine = OrbiittEngine()
72
+ logger.info("SIGLIP ENGINE ONLINE")
73
  except Exception as e:
74
  logger.error(f"ENGINE ERROR: {e}")
75
 
76
  @app.get("/")
77
  def health():
78
  imgs = os.listdir(IMAGE_DIR) if os.path.exists(IMAGE_DIR) else []
79
+ return {"engine": engine is not None, "db": os.path.exists(DB_TARGET), "img_count": len(imgs)}
 
 
 
 
 
80
 
81
  @app.post("/search")
82
  async def search(text: str = Form(None), weight: float = Form(0.5), file: UploadFile = File(None)):
83
+ if not engine: raise HTTPException(503, detail="AI Engine Loading")
84
  t_path = None
85
  try:
86
  if file:
 
89
 
90
  results = engine.search(text_query=text, image_file=t_path, text_weight=weight)
91
 
92
+ # 3. PATH SANITIZER: Converts internal paths to public browser URLs
93
  for r in results:
94
+ raw_path = r.get('url') or r.get('path') or ""
95
+ filename = os.path.basename(raw_path)
96
+ r['url'] = f"Productimages/{urllib.parse.quote(filename)}"
97
 
98
  return {"results": results}
99
  except Exception as e: