Spaces:
Paused
Paused
Create app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import osfrom flask import Flask, render_template, request, jsonify# Importing Memvid based on the SDK package namefrom memvid import Memvid
app = Flask(__name__)
# CONFIGURATION# We store the .mv2 file in a writable path. # On HF Spaces, /tmp is writable, or you can use the current directory # if you don't need persistence across reboots.DB_PATH = "knowledge.mv2"
# Initialize Memvid# We use a global variable to hold the referencetry: # Attempt to open or create. # Python SDK usually follows: Memvid(path) or Memvid.create(path) # Adjust this line based on exact SDK docs. if os.path.exists(DB_PATH): db = Memvid.open(DB_PATH) else: db = Memvid.create(DB_PATH) print(f"Memvid loaded at {DB_PATH}")except Exception as e: print(f"Error initializing Memvid: {e}") db = None
@app.route('/')def index(): return render_template('index.html')
@app.route('/add', methods=['POST'])def add_memory(): if not db: return jsonify({"error": "Database not initialized"}), 500
content = request.form.get('content') tags = request.form.get('tags', '') if not content: return jsonify({"error": "No content provided"}), 400
try: # Assuming the Python SDK has a .put() or .add() method # and accepts string content. # We simulate "PutOptions" via kwargs or a dict. db.put(content, tags=tags) # Depending on the SDK, you might need an explicit commit # db.commit() return jsonify({"success": True, "message": "Memory added successfully."}) except Exception as e: return jsonify({"error": str(e)}), 500
@app.route('/search', methods=['POST'])def search_memory(): if not db: return jsonify({"error": "Database not initialized"}), 500
query = request.form.get('query') if not query: return jsonify({"error": "No query provided"}), 400
try: # Perform search. Assuming .search returns a list of result objects results = db.search(query, top_k=5) # Format results for JSON # Assuming results have .text and .score attributes formatted_results = [] for hit in results: formatted_results.append({ "text": hit.text, # "score": hit.score # specific attributes depend on SDK }) return jsonify({"success": True, "results": formatted_results}) except Exception as e: return jsonify({"error": str(e)}), 500
if __name__ == '__main__': # Hugging Face Spaces runs on port 7860 by default app.run(host='0.0.0.0', port=7860)app.pyAdded+86