aniketkumar1106 commited on
Commit
ca04ee5
·
verified ·
1 Parent(s): cd1d7b0

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +42 -24
server.py CHANGED
@@ -1,65 +1,83 @@
1
- from fastapi import FastAPI, File, UploadFile, Form
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.staticfiles import StaticFiles
4
  import shutil
5
  import os
6
  import uvicorn
7
 
8
- # 1. Initialize the App (Only ONCE)
9
- app = FastAPI()
10
 
11
- # 2. CORS Middleware
12
  app.add_middleware(
13
  CORSMiddleware,
14
  allow_origins=["*"],
 
15
  allow_methods=["*"],
16
  allow_headers=["*"],
17
  )
18
 
19
- # 3. Ensure the images directory exists BEFORE mounting
20
  IMAGE_DIR = "Productimages"
21
  if not os.path.exists(IMAGE_DIR):
22
  os.makedirs(IMAGE_DIR)
23
 
24
  app.mount(f"/{IMAGE_DIR}", StaticFiles(directory=IMAGE_DIR), name=IMAGE_DIR)
25
 
26
- # 4. Import and Load Engine
27
- # We wrap this in try-except because a 4GB model often causes memory errors
28
  try:
29
  from orbiitt_engine import OrbiittEngine
30
  engine = OrbiittEngine()
31
- print("Engine loaded successfully.")
32
  except Exception as e:
33
- print(f"CRITICAL: Failed to load engine: {e}")
34
  engine = None
35
 
36
  @app.get("/")
37
  def read_root():
38
  return {
39
- "status": "online",
40
- "engine_loaded": engine is not None,
41
- "current_dir": os.getcwd(),
42
- "files_visible": os.listdir(".")
43
  }
44
 
45
  @app.post("/search")
46
- async def search_endpoint(text: str = Form(None), weight: float = Form(0.5), file: UploadFile = File(None)):
 
 
 
 
47
  if engine is None:
48
- return {"error": "Engine not initialized"}
49
-
50
- temp_path = None
51
- if file:
52
- temp_path = f"temp_{file.filename}"
53
- with open(temp_path, "wb") as buffer:
54
- shutil.copyfileobj(file.file, buffer)
55
 
 
56
  try:
57
- results = engine.search(text_query=text, image_file=temp_path, text_weight=weight)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  finally:
 
59
  if temp_path and os.path.exists(temp_path):
60
  os.remove(temp_path)
61
-
62
- return {"results": results}
63
 
 
64
  if __name__ == "__main__":
65
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
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 uvicorn
7
 
8
+ # 1. Initialize the app (Only ONCE)
9
+ app = FastAPI(title="ORBIT Visual Commerce API")
10
 
11
+ # 2. Correct CORS Configuration (Crucial for Netlify)
12
  app.add_middleware(
13
  CORSMiddleware,
14
  allow_origins=["*"],
15
+ allow_credentials=True,
16
  allow_methods=["*"],
17
  allow_headers=["*"],
18
  )
19
 
20
+ # 3. Ensure the static folder exists BEFORE mounting
21
  IMAGE_DIR = "Productimages"
22
  if not os.path.exists(IMAGE_DIR):
23
  os.makedirs(IMAGE_DIR)
24
 
25
  app.mount(f"/{IMAGE_DIR}", StaticFiles(directory=IMAGE_DIR), name=IMAGE_DIR)
26
 
27
+ # 4. Initialize the Engine
28
+ # Note: This will load your 4GB model into RAM
29
  try:
30
  from orbiitt_engine import OrbiittEngine
31
  engine = OrbiittEngine()
32
+ print("Successfully loaded OrbiittEngine.")
33
  except Exception as e:
34
+ print(f"Error loading OrbiittEngine: {e}")
35
  engine = None
36
 
37
  @app.get("/")
38
  def read_root():
39
  return {
40
+ "message": "Server is running",
41
+ "engine_status": "Ready" if engine else "Loading/Error",
42
+ "endpoints": ["/search", "/Productimages"]
 
43
  }
44
 
45
  @app.post("/search")
46
+ async def search_endpoint(
47
+ text: str = Form(None),
48
+ weight: float = Form(0.5),
49
+ file: UploadFile = File(None)
50
+ ):
51
  if engine is None:
52
+ raise HTTPException(status_code=503, detail="Engine not initialized")
 
 
 
 
 
 
53
 
54
+ temp_path = None
55
  try:
56
+ if file:
57
+ # Use a unique temp name to avoid collisions
58
+ temp_path = f"temp_{file.filename}"
59
+ with open(temp_path, "wb") as buffer:
60
+ # Correctly read the async file content
61
+ content = await file.read()
62
+ buffer.write(content)
63
+
64
+ # Call the search engine
65
+ results = engine.search(
66
+ text_query=text,
67
+ image_file=temp_path,
68
+ text_weight=weight
69
+ )
70
+ return {"results": results}
71
+
72
+ except Exception as e:
73
+ print(f"Search error: {e}")
74
+ raise HTTPException(status_code=500, detail=str(e))
75
+
76
  finally:
77
+ # Always clean up the temp file
78
  if temp_path and os.path.exists(temp_path):
79
  os.remove(temp_path)
 
 
80
 
81
+ # Corrected the execution block
82
  if __name__ == "__main__":
83
  uvicorn.run(app, host="0.0.0.0", port=7860)