from fastapi import FastAPI, UploadFile, File, HTTPException from fastapi.responses import JSONResponse import shutil import os from vasrch import search_similar_images # Initialize the FastAPI app app = FastAPI() # Define paths UPLOAD_FOLDER = "uploaded_images" MODEL_FILENAME = "kmeans_model_100.pkl" CSV_FILE = "cluster_assignments_100.csv" # Ensure the upload folder exists os.makedirs(UPLOAD_FOLDER, exist_ok=True) @app.post("/search-by-image") async def find_similar_images(file: UploadFile = File(...), top_n: int = 30): try: # Save the uploaded file to the upload folder file_path = os.path.join(UPLOAD_FOLDER, file.filename) with open(file_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer) # Call the search_similar_images function similar_images = search_similar_images(file_path, MODEL_FILENAME, CSV_FILE, top_n) # Return the similar images in JSON format return JSONResponse(content={"similar_images": similar_images}) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: # Clean up the uploaded file if os.path.exists(file_path): os.remove(file_path) @app.get("/hello") async def hello(): return {"message": "Image search server is up and running"} # Run the app with uvicorn # Command: uvicorn fastapi_image_search:app --reload