aniketkumar1106 commited on
Commit
1c253ff
Β·
verified Β·
1 Parent(s): 6063744

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +33 -20
server.py CHANGED
@@ -9,13 +9,23 @@ from fastapi.middleware.cors import CORSMiddleware
9
  from fastapi.staticfiles import StaticFiles
10
  from huggingface_hub import snapshot_download
11
 
12
- # Setup Logging
13
  logging.basicConfig(level=logging.INFO)
14
  logger = logging.getLogger(__name__)
15
 
 
 
 
 
 
 
 
 
 
 
 
16
  app = FastAPI()
17
 
18
- # Enable CORS for Hugging Face environment
19
  app.add_middleware(
20
  CORSMiddleware,
21
  allow_origins=["*"],
@@ -24,19 +34,16 @@ app.add_middleware(
24
  allow_headers=["*"],
25
  )
26
 
27
- DATASET_REPO = "aniketkumar1106/orbit-data"
28
- IMAGE_DIR = "Productimages"
29
- DB_TARGET = "orbiitt.db"
30
 
31
- # Global state
32
  engine = None
33
- loading_status = "System Initializing..."
34
 
35
  def normalize_filename(name):
36
- """Handles smart quotes, Unicode characters, and URL-unsafe symbols."""
37
- # Convert curly quotes/dashes to standard ASCII
38
  name = name.replace('’', "'").replace('β€˜', "'").replace('β€œ', '"').replace('”', '"').replace('–', '-')
39
- # Decompose Unicode characters and strip non-ASCII
40
  name = unicodedata.normalize('NFKD', name).encode('ascii', 'ignore').decode('ascii')
41
  return name.strip()
42
 
@@ -45,11 +52,14 @@ def setup_environment():
45
  global engine, loading_status
46
  token = os.environ.get("HF_TOKEN")
47
 
48
- if os.path.exists(IMAGE_DIR): shutil.rmtree(IMAGE_DIR)
49
- os.makedirs(IMAGE_DIR)
 
 
50
 
51
  try:
52
  loading_status = "Syncing Orbit Assets..."
 
53
  snapshot_download(repo_id=DATASET_REPO, repo_type="dataset", token=token, local_dir=".")
54
 
55
  if os.path.exists("orbiitt_db.zip"):
@@ -62,12 +72,13 @@ def setup_environment():
62
  if f.lower() in ["orbiitt_db", "orbiitt.db"] or (f.endswith(".db") and not f.startswith(".")):
63
  shutil.copy(src, f"./{DB_TARGET}")
64
  elif f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
65
- # Clean name to prevent 404 mismatches
66
  clean_name = normalize_filename(urllib.parse.unquote(f))
67
  shutil.copy(src, os.path.join(IMAGE_DIR, clean_name))
68
  shutil.rmtree("temp_extract")
69
 
70
- loading_status = "Loading SigLIP 2 AI Model..."
 
71
  try:
72
  from orbiitt_engine import OrbiittEngine
73
  engine = OrbiittEngine()
@@ -79,8 +90,7 @@ def setup_environment():
79
 
80
  except Exception as e:
81
  loading_status = f"Setup Failed: {e}"
82
-
83
- app.mount("/Productimages", StaticFiles(directory=IMAGE_DIR), name="Productimages")
84
 
85
  @app.get("/health")
86
  def health():
@@ -95,11 +105,11 @@ async def search(text: str = Form(None), weight: float = Form(0.5), file: Upload
95
  try:
96
  if file:
97
  t_path = f"tmp_{file.filename}"
98
- with open(t_path, "wb") as b: b.write(await file.read())
 
99
 
100
  results = engine.search(text_query=text, image_file=t_path, text_weight=weight)
101
 
102
- # Fuzzy match results against disk to ensure valid URLs
103
  all_files = os.listdir(IMAGE_DIR)
104
  valid_results = []
105
 
@@ -107,12 +117,13 @@ async def search(text: str = Form(None), weight: float = Form(0.5), file: Upload
107
  raw_path = r.get('url') or r.get('path') or ""
108
  fname = normalize_filename(os.path.basename(raw_path))
109
 
 
110
  match = None
111
  if fname in all_files:
112
  match = fname
113
  else:
114
  for disk_file in all_files:
115
- if fname[:20] in disk_file: # Substring fallback
116
  match = disk_file
117
  break
118
 
@@ -122,9 +133,11 @@ async def search(text: str = Form(None), weight: float = Form(0.5), file: Upload
122
 
123
  return {"results": valid_results}
124
  except Exception as e:
 
125
  return {"results": [], "error": str(e)}
126
  finally:
127
- if t_path and os.path.exists(t_path): os.remove(t_path)
 
128
 
129
  if __name__ == "__main__":
130
  import uvicorn
 
9
  from fastapi.staticfiles import StaticFiles
10
  from huggingface_hub import snapshot_download
11
 
12
+ # 1. SETUP LOGGING
13
  logging.basicConfig(level=logging.INFO)
14
  logger = logging.getLogger(__name__)
15
 
16
+ # 2. DEFINE PATHS
17
+ DATASET_REPO = "aniketkumar1106/orbit-data"
18
+ IMAGE_DIR = "Productimages"
19
+ DB_TARGET = "orbiitt.db"
20
+
21
+ # 3. CRITICAL FIX: Create directory BEFORE FastAPI initialization
22
+ if not os.path.exists(IMAGE_DIR):
23
+ os.makedirs(IMAGE_DIR, exist_ok=True)
24
+ logger.info(f"Created initial directory: {IMAGE_DIR}")
25
+
26
+ # 4. INITIALIZE APP
27
  app = FastAPI()
28
 
 
29
  app.add_middleware(
30
  CORSMiddleware,
31
  allow_origins=["*"],
 
34
  allow_headers=["*"],
35
  )
36
 
37
+ # 5. MOUNT STORAGE (Will no longer crash)
38
+ app.mount("/Productimages", StaticFiles(directory=IMAGE_DIR), name="Productimages")
 
39
 
40
+ # 6. GLOBAL ENGINE STATE
41
  engine = None
42
+ loading_status = "System Booting..."
43
 
44
  def normalize_filename(name):
45
+ """Handles smart quotes and complex symbols to prevent 404s."""
 
46
  name = name.replace('’', "'").replace('β€˜', "'").replace('β€œ', '"').replace('”', '"').replace('–', '-')
 
47
  name = unicodedata.normalize('NFKD', name).encode('ascii', 'ignore').decode('ascii')
48
  return name.strip()
49
 
 
52
  global engine, loading_status
53
  token = os.environ.get("HF_TOKEN")
54
 
55
+ # We clean and re-create inside startup to ensure a fresh sync
56
+ if os.path.exists(IMAGE_DIR):
57
+ shutil.rmtree(IMAGE_DIR)
58
+ os.makedirs(IMAGE_DIR, exist_ok=True)
59
 
60
  try:
61
  loading_status = "Syncing Orbit Assets..."
62
+ logger.info(loading_status)
63
  snapshot_download(repo_id=DATASET_REPO, repo_type="dataset", token=token, local_dir=".")
64
 
65
  if os.path.exists("orbiitt_db.zip"):
 
72
  if f.lower() in ["orbiitt_db", "orbiitt.db"] or (f.endswith(".db") and not f.startswith(".")):
73
  shutil.copy(src, f"./{DB_TARGET}")
74
  elif f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
75
+ # Normalize filename on disk
76
  clean_name = normalize_filename(urllib.parse.unquote(f))
77
  shutil.copy(src, os.path.join(IMAGE_DIR, clean_name))
78
  shutil.rmtree("temp_extract")
79
 
80
+ loading_status = "Waking up AI Engine..."
81
+ logger.info(loading_status)
82
  try:
83
  from orbiitt_engine import OrbiittEngine
84
  engine = OrbiittEngine()
 
90
 
91
  except Exception as e:
92
  loading_status = f"Setup Failed: {e}"
93
+ logger.error(loading_status)
 
94
 
95
  @app.get("/health")
96
  def health():
 
105
  try:
106
  if file:
107
  t_path = f"tmp_{file.filename}"
108
+ with open(t_path, "wb") as b:
109
+ b.write(await file.read())
110
 
111
  results = engine.search(text_query=text, image_file=t_path, text_weight=weight)
112
 
 
113
  all_files = os.listdir(IMAGE_DIR)
114
  valid_results = []
115
 
 
117
  raw_path = r.get('url') or r.get('path') or ""
118
  fname = normalize_filename(os.path.basename(raw_path))
119
 
120
+ # Fuzzy match check
121
  match = None
122
  if fname in all_files:
123
  match = fname
124
  else:
125
  for disk_file in all_files:
126
+ if fname[:20] in disk_file:
127
  match = disk_file
128
  break
129
 
 
133
 
134
  return {"results": valid_results}
135
  except Exception as e:
136
+ logger.error(f"Search error: {e}")
137
  return {"results": [], "error": str(e)}
138
  finally:
139
+ if t_path and os.path.exists(t_path):
140
+ os.remove(t_path)
141
 
142
  if __name__ == "__main__":
143
  import uvicorn