|
import gradio as gr |
|
import os |
|
import faiss |
|
import numpy as np |
|
from pathlib import Path |
|
import shutil |
|
|
|
|
|
DATA_DIR = "data" |
|
INDEX_PATH = os.path.join(DATA_DIR, "faiss_index.index") |
|
|
|
def save_index(file_obj): |
|
""" |
|
Save uploaded FAISS index to the data directory |
|
""" |
|
|
|
Path(DATA_DIR).mkdir(exist_ok=True) |
|
|
|
|
|
if os.path.exists(INDEX_PATH): |
|
return "⚠️ A FAISS index already exists in the data directory. Please remove it first." |
|
|
|
try: |
|
|
|
shutil.copy2(file_obj.name, INDEX_PATH) |
|
|
|
|
|
faiss.read_index(INDEX_PATH) |
|
return "✅ FAISS index successfully uploaded and saved!" |
|
|
|
except Exception as e: |
|
|
|
if os.path.exists(INDEX_PATH): |
|
os.remove(INDEX_PATH) |
|
return f"❌ Error: Invalid FAISS index file - {str(e)}" |
|
|
|
|
|
demo = gr.Interface( |
|
fn=save_index, |
|
inputs=gr.File(label="Upload FAISS Index", file_types=[".index"]), |
|
outputs=gr.Textbox(label="Status"), |
|
title="FAISS Index Uploader", |
|
description="Upload a FAISS index file to store in the HuggingFace Space data directory.", |
|
allow_flagging="never" |
|
) |
|
|
|
if __name__ == "__main__": |
|
demo.launch() |