aniketkumar1106 commited on
Commit
a52126c
·
verified ·
1 Parent(s): a2f4ac8

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +76 -47
server.py CHANGED
@@ -1,13 +1,14 @@
 
 
 
1
  from fastapi import FastAPI, File, UploadFile, Form, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.staticfiles import StaticFiles
4
- import shutil
5
- import os
6
- import zipfile
7
- import uvicorn
8
 
9
- app = FastAPI(title="ORBIT Visual Commerce API")
10
 
 
11
  app.add_middleware(
12
  CORSMiddleware,
13
  allow_origins=["*"],
@@ -16,68 +17,96 @@ app.add_middleware(
16
  allow_headers=["*"],
17
  )
18
 
19
- # --- NEW: UNZIP LOGIC ---
20
- def extract_resources():
21
- # Change 'data.zip' to the actual name of your zip file
22
- zip_name = "data.zip"
23
-
24
- if os.path.exists(zip_name):
25
- print(f"Extracting {zip_name}...")
26
- with zipfile.ZipFile(zip_name, 'r') as zip_ref:
27
- zip_ref.extractall(".")
28
- print("Extraction complete.")
29
- else:
30
- print(f"Note: {zip_name} not found, skipping extraction.")
31
 
32
- # Run extraction before anything else
33
- extract_resources()
 
 
 
 
34
 
35
- # --- SETUP DIRECTORIES ---
36
- IMAGE_DIR = "Productimages"
37
- if not os.path.exists(IMAGE_DIR):
38
- os.makedirs(IMAGE_DIR)
 
 
 
 
 
 
39
 
40
- app.mount(f"/{IMAGE_DIR}", StaticFiles(directory=IMAGE_DIR), name=IMAGE_DIR)
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- # --- LOAD ENGINE ---
 
 
 
 
 
 
 
 
43
  try:
44
  from orbiitt_engine import OrbiittEngine
45
- # The engine should now find orbiitt.db in the root folder
46
  engine = OrbiittEngine()
47
- print("OrbiittEngine initialized successfully.")
48
  except Exception as e:
49
- print(f"Error loading OrbiittEngine: {e}")
50
- engine = None
51
 
52
  @app.get("/")
53
- def read_root():
54
- # Diagnostic: Check if the DB file exists now
55
- db_exists = os.path.exists("orbiitt.db")
56
  return {
57
- "message": "Server is running",
58
- "db_found": db_exists,
59
- "engine_ready": engine is not None,
60
- "files_in_root": os.listdir(".")[:10] # Shows first 10 files for debugging
61
  }
62
 
63
  @app.post("/search")
64
- async def search_endpoint(text: str = Form(None), weight: float = Form(0.5), file: UploadFile = File(None)):
65
- if engine is None:
66
- raise HTTPException(status_code=503, detail="Engine not loaded")
67
 
68
- temp_path = None
69
  try:
 
70
  if file:
71
- temp_path = f"temp_{file.filename}"
72
- with open(temp_path, "wb") as buffer:
73
- content = await file.read()
74
- buffer.write(content)
75
 
76
- results = engine.search(text_query=text, image_file=temp_path, text_weight=weight)
 
77
  return {"results": results}
 
 
 
 
78
  finally:
79
- if temp_path and os.path.exists(temp_path):
80
- os.remove(temp_path)
 
81
 
82
  if __name__ == "__main__":
 
 
83
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ import os
2
+ import zipfile
3
+ import shutil
4
  from fastapi import FastAPI, File, UploadFile, Form, HTTPException
5
  from fastapi.middleware.cors import CORSMiddleware
6
  from fastapi.staticfiles import StaticFiles
7
+ from huggingface_hub import hf_hub_download
 
 
 
8
 
9
+ app = FastAPI(title="ORBIT Visual Search Engine")
10
 
11
+ # 1. Enable Global CORS (Crucial for Netlify)
12
  app.add_middleware(
13
  CORSMiddleware,
14
  allow_origins=["*"],
 
17
  allow_headers=["*"],
18
  )
19
 
20
+ # --- CONFIGURATION ---
21
+ DATASET_REPO = "aniketkumar1106/your-private-dataset" # CHANGE THIS
22
+ ZIP_FILENAME = "product_data.zip" # CHANGE THIS
23
+ IMAGE_DIR = "Productimages"
24
+ DB_FILE = "orbiitt.db"
 
 
 
 
 
 
 
25
 
26
+ def initialize_backend():
27
+ """Downloads and unzips data from a private dataset on startup."""
28
+ token = os.environ.get("HF_TOKEN")
29
+ if not token:
30
+ print("CRITICAL: HF_TOKEN secret is missing from Space Settings!")
31
+ return
32
 
33
+ try:
34
+ # Download the zip file into the current directory
35
+ print(f"Fetching {ZIP_FILENAME} from private dataset...")
36
+ zip_path = hf_hub_download(
37
+ repo_id=DATASET_REPO,
38
+ filename=ZIP_FILENAME,
39
+ repo_type="dataset",
40
+ token=token,
41
+ local_dir="."
42
+ )
43
 
44
+ # Extract everything
45
+ print("Extracting archive...")
46
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref:
47
+ zip_ref.extractall(".")
48
+
49
+ # Ensure the image folder exists for mounting
50
+ if not os.path.exists(IMAGE_DIR):
51
+ os.makedirs(IMAGE_DIR)
52
+
53
+ print(f"Setup complete. Found {len(os.listdir(IMAGE_DIR))} images.")
54
+ except Exception as e:
55
+ print(f"Startup Error: {e}")
56
 
57
+ # Trigger extraction before app starts
58
+ initialize_backend()
59
+
60
+ # 2. Mount Static Files (Must happen after directory is created)
61
+ if os.path.exists(IMAGE_DIR):
62
+ app.mount(f"/{IMAGE_DIR}", StaticFiles(directory=IMAGE_DIR), name=IMAGE_DIR)
63
+
64
+ # 3. Load the Engine (Handles your 4GB weights)
65
+ engine = None
66
  try:
67
  from orbiitt_engine import OrbiittEngine
68
+ # The engine should now find orbiitt.db in the root
69
  engine = OrbiittEngine()
70
+ print("OrbiittEngine successfully initialized.")
71
  except Exception as e:
72
+ print(f"Engine Load Error: {e}")
 
73
 
74
  @app.get("/")
75
+ def health_check():
76
+ """Diagnostic endpoint to check file health."""
 
77
  return {
78
+ "status": "online",
79
+ "database_ready": os.path.exists(DB_FILE),
80
+ "images_count": len(os.listdir(IMAGE_DIR)) if os.path.exists(IMAGE_DIR) else 0,
81
+ "engine_loaded": engine is not None
82
  }
83
 
84
  @app.post("/search")
85
+ async def search(text: str = Form(None), weight: float = Form(0.5), file: UploadFile = File(None)):
86
+ if not engine:
87
+ raise HTTPException(status_code=503, detail="Search engine is still loading or failed.")
88
 
89
+ temp_image = None
90
  try:
91
+ # Save incoming search image if provided
92
  if file:
93
+ temp_image = f"search_input_{file.filename}"
94
+ with open(temp_image, "wb") as buffer:
95
+ buffer.write(await file.read())
 
96
 
97
+ # Perform the actual model search
98
+ results = engine.search(text_query=text, image_file=temp_image, text_weight=weight)
99
  return {"results": results}
100
+
101
+ except Exception as e:
102
+ print(f"Runtime Search Error: {e}")
103
+ raise HTTPException(status_code=500, detail="Search failed internally.")
104
  finally:
105
+ # Clean up temporary search image
106
+ if temp_image and os.path.exists(temp_image):
107
+ os.remove(temp_image)
108
 
109
  if __name__ == "__main__":
110
+ import uvicorn
111
+ # Use standard port for Hugging Face Spaces
112
  uvicorn.run(app, host="0.0.0.0", port=7860)