Spaces:
Sleeping
Sleeping
Commit ·
538c3da
1
Parent(s): c97c61d
Dynamic source update endpoint
Browse filesFiles changed (2)
- app.py+83-10
- postman.json+45
2 unmodified lines34567814 unmodified lines232425262728298 unmodified lines383940414243120 unmodified lines164165166167168169134 unmodified lines3043053063073083093103113123133143153163173183193202 unmodified linesimport osimport loggingimport functoolsimport pandas as pdimport threadingimport time14 unmodified linesEXTERNAL_URL, URL_UPDATE_PERIOD_MINUTES, URL_FETCH_ENABLED,RAG_CSV_MAX_RESULTS, RAG_CSV_CONFIDENCE_THRESHOLD)from utils import download_and_unzip_gdrive_file, download_gdrive_file, fetch_and_clean_url# Logging Setuplogging.basicConfig(level=logging.INFO)8 unmodified linesuser_df = None_APP_BASE_DIR = os.path.dirname(os.path.abspath(__file__))# --- Helper: Load Users ---def load_users_from_csv():global user_df120 unmodified lineslogger.info(f"[URL_UPDATE] Triggering scheduled periodic update...")trigger_url_update()# --- Startup Logic ---def run_startup_tasks():global rag_system134 unmodified lines@app.route('/admin/rebuild_index', methods=['POST'])@require_admin_authdef rebuild_index():global rag_systemtry:if URL_FETCH_ENABLED and EXTERNAL_URL:result = trigger_url_update()if "error" in result:return jsonify(result), 500return jsonify({"status": "Index rebuilt successfully using combined local & URL sources"}), 200else:rag_system = initialize_and_get_rag_system(force_rebuild=True)return jsonify({"status": "Index rebuilt successfully"}), 200except Exception as e:return jsonify({"error": str(e)}), 500# Retained specific endpoint name to ensure the frontend doesn't break2 unmodified lines345678914 unmodified lines242526272829308 unmodified lines394041424344454647120 unmodified lines168169170171172173174175176177178179180181182183184185186187134 unmodified lines3223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923932 unmodified linesimport osimport loggingimport functoolsfrom datetime import datetimeimport pandas as pdimport threadingimport time14 unmodified linesEXTERNAL_URL, URL_UPDATE_PERIOD_MINUTES, URL_FETCH_ENABLED,RAG_CSV_MAX_RESULTS, RAG_CSV_CONFIDENCE_THRESHOLD)from utils import download_and_unzip_gdrive_file, download_gdrive_file, fetch_and_clean_url, FAISS_RAG_SUPPORTED_EXTENSIONS# Logging Setuplogging.basicConfig(level=logging.INFO)8 unmodified linesuser_df = None_APP_BASE_DIR = os.path.dirname(os.path.abspath(__file__))# Source file constantsSOURCES_ARCHIVE_DIR = os.path.join(_APP_BASE_DIR, 'sources_archive')# --- Helper: Load Users ---def load_users_from_csv():global user_df120 unmodified lineslogger.info(f"[URL_UPDATE] Triggering scheduled periodic update...")trigger_url_update()def rebuild_rag_system():global rag_systemif URL_FETCH_ENABLED and EXTERNAL_URL:result = trigger_url_update()if "error" in result:return resultreturn {"status": "Index rebuilt successfully using combined local & URL sources"}rag_system = initialize_and_get_rag_system(force_rebuild=True)if rag_system is None:return {"error": "Failed to rebuild RAG system"}return {"status": "Index rebuilt successfully"}# --- Startup Logic ---def run_startup_tasks():global rag_system134 unmodified lines@app.route('/admin/rebuild_index', methods=['POST'])@require_admin_authdef rebuild_index():try:result = rebuild_rag_system()if "error" in result:return jsonify(result), 500return jsonify(result), 200except Exception as e:return jsonify({"error": str(e)}), 500@app.route('/admin/upload/<path:filename>', methods=['POST'])@require_admin_authdef upload_vehicle_csv(filename):uploaded_file = request.files.get('file') or request.files.get('upload') or request.files.get('source_file')if not uploaded_file:return jsonify({"error": "No CSV file uploaded. Use multipart/form-data with field 'file'."}), 400safe_filename = os.path.basename((filename or '').strip())if not safe_filename or safe_filename != filename.strip():return jsonify({"error": "Invalid filename."}), 400file_ext = safe_filename.rsplit('.', 1)[-1].lower() if '.' in safe_filename else ''if file_ext not in FAISS_RAG_SUPPORTED_EXTENSIONS:supported_types = sorted(FAISS_RAG_SUPPORTED_EXTENSIONS.keys())return jsonify({"error": "Unsupported file type.","supported_extensions": supported_types}), 400os.makedirs(RAG_SOURCES_DIR, exist_ok=True)os.makedirs(SOURCES_ARCHIVE_DIR, exist_ok=True)target_path = os.path.join(RAG_SOURCES_DIR, safe_filename)temp_upload_path = os.path.join(RAG_SOURCES_DIR, f".{safe_filename}.uploading")archive_path = Nonetry:uploaded_file.save(temp_upload_path)if os.path.getsize(temp_upload_path) == 0:os.remove(temp_upload_path)return jsonify({"error": "Uploaded file is empty."}), 400if os.path.exists(target_path):timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')archive_dir = os.path.join(SOURCES_ARCHIVE_DIR, timestamp)os.makedirs(archive_dir, exist_ok=True)archive_path = os.path.join(archive_dir, safe_filename)shutil.move(target_path, archive_path)os.replace(temp_upload_path, target_path)result = rebuild_rag_system()if "error" in result:return jsonify(result), 500response_payload = {"status": "success","message": f"{safe_filename} uploaded and index rebuilt successfully.","filename": safe_filename,"saved_to": target_path,"archived_previous_to": archive_path}return jsonify(response_payload), 200except Exception as e:logger.error(f"[SOURCE_UPLOAD] Error updating {safe_filename}: {e}", exc_info=True)if os.path.exists(temp_upload_path):os.remove(temp_upload_path)return jsonify({"error": str(e)}), 500# Retained specific endpoint name to ensure the frontend doesn't break
124 unmodified lines125126127128129130124 unmodified lines},"response": []},{"name": "Public - Status","request": {124 unmodified lines125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175124 unmodified lines},"response": []},{"name": "Admin - Upload Source File","request": {"auth": {"type": "basic","basic": [{"key": "password","value": "1234","type": "string"},{"key": "username","value": "admin","type": "string"}]},"method": "POST","header": [],"body": {"mode": "formdata","formdata": [{"key": "file","type": "file","src": ""}]},"url": {"raw": "{{base_url}}/admin/upload/vehicle.csv","host": ["{{base_url}}"],"path": ["admin","upload","vehicle.csv"]},"description": "Uploads a replacement source file using the filename in the URL, archives the previous file with the same name, and rebuilds the index."},"response": []},{"name": "Public - Status","request": {
app.py+83-10
postman.json+45