~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
Get very basic enhanced log display to work.
Daniel Petti8538aa00a3e1
diff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.pyindex 49627db8cf..c56f892518 100644--- a/src/local_deep_research/utilities/log_utils.py+++ b/src/local_deep_research/utilities/log_utils.py@@ -17,7 +17,7 @@ from flask import g, has_app_contextfrom loguru import loggerfrom ..web.database.models import ResearchLog-from ..web.services.socket_service import emit_to_subscribers+from ..web.services.socket_service import SocketIOServicefrom .db_utils import get_db_session_LOG_DIR = Path(__file__).parents[2] / "data" / "logs"@@ -141,7 +141,7 @@ def frontend_progress_sink(message: loguru.Message) -> None:time=record["time"].isoformat(),),)- emit_to_subscribers("progress", research_id, frontend_log)+ SocketIOService().emit_to_subscribers("progress", research_id, frontend_log)def config_logger(name: str) -> None:diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.pyindex 7f23594fd6..4ef8c490ba 100644--- a/src/local_deep_research/web/app.py+++ b/src/local_deep_research/web/app.py@@ -92,15 +92,8 @@ def main():host = get_db_setting("web.host", "0.0.0.0")debug = get_db_setting("web.debug", True)- logger.info(f"Starting web server on {host}:{port} (debug: {debug})")- socketio.run(- app,- debug=debug,- host=host,- port=port,- allow_unsafe_werkzeug=True,- use_reloader=False,- )+ with app.app_context():+ socketio.run(host, port, debug=debug)if __name__ == "__main__":diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex c7b9336bb6..0bd0f8f119 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -16,7 +16,7 @@ from loguru import loggerfrom ..utilities.log_utils import InterceptHandlerfrom .models.database import DB_PATH, init_db-from .services.socket_service import get_socketio+from .services.socket_service import SocketIOServicedef create_app():@@ -70,7 +70,7 @@ def create_app():init_db()# Register socket service- socketio = get_socketio(app)+ socket_service = SocketIOService(app=app)# Apply middlewareapply_middleware(app)@@ -81,10 +81,7 @@ def create_app():# Register error handlersregister_error_handlers(app)- # Register socket event handlers- register_socket_events(socketio)-- return app, socketio+ return app, socket_servicedef apply_middleware(app):@@ -178,41 +175,6 @@ def register_error_handlers(app):return make_response(jsonify({"error": "Server error"}), 500)-def register_socket_events(socketio):- """Register Socket.IO event handlers."""-- from .routes.research_routes import get_globals- from .services.socket_service import (- handle_connect,- handle_default_error,- handle_disconnect,- handle_socket_error,- handle_subscribe,- )-- @socketio.on("connect")- def on_connect():- handle_connect(request)-- @socketio.on("disconnect")- def on_disconnect(reason: str):- handle_disconnect(request, reason)-- @socketio.on("subscribe_to_research")- def on_subscribe(data):- globals_dict = get_globals()- active_research = globals_dict.get("active_research", {})- handle_subscribe(data, request, active_research)-- @socketio.on_error- def on_error(e):- return handle_socket_error(e)-- @socketio.on_error_default- def on_default_error(e):- return handle_default_error(e)--def create_database(app):"""Create the database and tables for the application.diff --git a/src/local_deep_research/web/models/database.py b/src/local_deep_research/web/models/database.pyindex e32f171604..a3ba8f7b91 100644--- a/src/local_deep_research/web/models/database.py+++ b/src/local_deep_research/web/models/database.py@@ -1,10 +1,12 @@-import jsonimport osimport sqlite3from datetime import datetimefrom loguru import logger+from ...utilities.db_utils import get_db_session+from ..database.models import ResearchLog+# Database path# Use unified database in data directoryDATA_DIR = os.path.abspath(@@ -223,35 +225,21 @@ def get_logs_for_research(research_id):List of log entries as dictionaries"""try:- conn = get_db_connection()- conn.row_factory = sqlite3.Row- cursor = conn.cursor()- cursor.execute(- "SELECT * FROM research_logs WHERE research_id = ? ORDER BY timestamp ASC",- (research_id,),+ session = get_db_session()+ log_results = (+ session.query(ResearchLog)+ .filter(ResearchLog.research_id == research_id)+ .order_by(ResearchLog.timestamp.asc())+ .all())- results = cursor.fetchall()- conn.close()logs = []- for result in results:- log_entry = dict(result)- # Parse metadata JSON if it exists- if log_entry.get("metadata"):- try:- log_entry["metadata"] = json.loads(log_entry["metadata"])- except Exception:- log_entry["metadata"] = {}- else:- log_entry["metadata"] = {}-+ for result in log_results:# Convert entry for frontend consumptionformatted_entry = {- "time": log_entry["timestamp"],- "message": log_entry["message"],- "progress": log_entry["progress"],- "metadata": log_entry["metadata"],- "type": log_entry["log_type"],+ "time": result.timestamp,+ "message": result.message,+ "type": result.level,}logs.append(formatted_entry)diff --git a/src/local_deep_research/web/routes/globals.py b/src/local_deep_research/web/routes/globals.pynew file mode 100644index 0000000000..7eced1386a--- /dev/null+++ b/src/local_deep_research/web/routes/globals.py@@ -0,0 +1,22 @@+"""+Stores global state.+"""++# Active research processes and socket subscriptions+active_research = {}+socket_subscriptions = {}+# Add termination flags dictionary+termination_flags = {}+++def get_globals():+ """+ Returns:+ Global state for other modules to access.++ """+ return {+ "active_research": active_research,+ "socket_subscriptions": socket_subscriptions,+ "termination_flags": termination_flags,+ }diff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.pyindex 9d136aed19..f5ab23f0c1 100644--- a/src/local_deep_research/web/routes/history_routes.py+++ b/src/local_deep_research/web/routes/history_routes.py@@ -6,6 +6,7 @@ from pathlib import Pathfrom flask import Blueprint, jsonify, make_responsefrom ..models.database import get_db_connection, get_logs_for_research+from ..routes.globals import get_globals# Initialize loggerlogger = logging.getLogger(__name__)@@ -157,9 +158,6 @@ def get_research_status(research_id):if not result:return jsonify({"status": "error", "message": "Research not found"}), 404- # Import globals from research routes- from .research_routes import get_globals-globals_dict = get_globals()active_research = globals_dict["active_research"]@@ -201,9 +199,6 @@ def get_research_details(research_id):# Get logs from the dedicated log databaselogs = get_logs_for_research(research_id)- # Import globals from research routes- from .research_routes import get_globals-globals_dict = get_globals()active_research = globals_dict["active_research"]@@ -346,30 +341,4 @@ def get_research_logs(research_id):}formatted_logs.append(log_entry)- # Import globals from research routes- from .research_routes import get_globals-- globals_dict = get_globals()- active_research = globals_dict["active_research"]-- # Add any current logs from memory if this is an active research- if research_id in active_research and active_research[research_id].get("log"):- # Use the logs from memory temporarily until they're saved to the database- memory_logs = active_research[research_id]["log"]-- # Format memory logs too- for log in memory_logs:- log_entry = {- "time": log.get("time", ""),- "message": log.get("message", "No message"),- "type": log.get("type", "info"),- }-- # Check if this log is already in our formatted logs by timestamp- if not any(flog["time"] == log_entry["time"] for flog in formatted_logs):- formatted_logs.append(log_entry)-- # Sort logs by timestamp- formatted_logs.sort(key=lambda x: x["time"])-return jsonify({"status": "success", "logs": formatted_logs})diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex ff1b351741..c48925db2e 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -18,30 +18,15 @@ from loguru import loggerfrom ..models.database import calculate_duration, get_db_connectionfrom ..services.research_service import run_research_process, start_research_processfrom ..utils.templates import render_template_with_defaults+from .globals import active_research, termination_flags# Create a Blueprint for the research applicationresearch_bp = Blueprint("research", __name__, url_prefix="/research")-# Active research processes and socket subscriptions-active_research = {}-socket_subscriptions = {}--# Add termination flags dictionary-termination_flags = {}-# Output directory for research resultsOUTPUT_DIR = "research_outputs"-# Return reference to globals for other modules to access-def get_globals():- return {- "active_research": active_research,- "socket_subscriptions": socket_subscriptions,- "termination_flags": termination_flags,- }--# Route for index page - redirection@research_bp.route("/")def index():diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 1445288d30..f6df007db9 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -15,7 +15,7 @@ from ...utilities.log_utils import log_for_researchfrom ...utilities.search_utilities import extract_links_from_search_resultsfrom ...utilities.threading_utils import thread_context, thread_with_app_contextfrom ..models.database import calculate_duration, get_db_connection-from .socket_service import emit_to_subscribers+from .socket_service import SocketIOService# Output directory for research results_PROJECT_ROOT = Path(__file__).parents[4]@@ -265,7 +265,9 @@ def run_research_process(# Basic event dataevent_data = {"message": message, "progress": adjusted_progress}- emit_to_subscribers("progress", research_id, event_data)+ SocketIOService().emit_to_subscribers(+ "progress", research_id, event_data+ )except Exception:logger.exception("Socket emit error (non-critical)")@@ -784,7 +786,7 @@ def run_research_process(conn.close()try:- emit_to_subscribers(+ SocketIOService().emit_to_subscribers("research_progress",research_id,{"status": status, "error": message},@@ -836,7 +838,7 @@ def cleanup_research_resources(research_id, active_research, termination_flags):# Send a final message to subscriberstry:# Import here to avoid circular imports- from ..routes.research_routes import get_globals+ from ..routes.globals import get_globalsglobals_dict = get_globals()socket_subscriptions = globals_dict.get("socket_subscriptions", {})@@ -863,7 +865,9 @@ def cleanup_research_resources(research_id, active_research, termination_flags):research_id,)- emit_to_subscribers("research_progress", research_id, final_message)+ SocketIOService().emit_to_subscribers(+ "research_progress", research_id, final_message+ )except Exception:logger.error("Error sending final cleanup message")@@ -919,7 +923,7 @@ def cancel_research(research_id):bool: True if the research was found and cancelled, False otherwise"""# Import globals from research routes- from ..routes.research_routes import get_globals+ from ..routes.globals import get_globalsglobals_dict = get_globals()active_research = globals_dict["active_research"]diff --git a/src/local_deep_research/web/services/socket_service.py b/src/local_deep_research/web/services/socket_service.pyindex abb89e88a5..4fb994a102 100644--- a/src/local_deep_research/web/services/socket_service.py+++ b/src/local_deep_research/web/services/socket_service.py@@ -1,218 +1,283 @@-from functools import cache+from datetime import datetime+from typing import Any, NoReturn-from cachetools import LRUCache-from flask import Flask, current_app+from flask import Flask, current_app, requestfrom flask_socketio import SocketIOfrom loguru import logger-from ...utilities.threading_utils import thread_specific_cache+from ..models.database import get_db_connection+from ..routes.globals import get_globals-# Socket subscription tracking-socket_subscriptions = {}---# @thread_specific_cache(LRUCache(maxsize=1))-@cache-def get_socketio(app: Flask | None = None) -> SocketIO:- """- Get the Socket.IO instance for the service.-- Args:- app: The flask app to use. If not specified, it will- default to the current app from the request context.+class SocketIOService:"""- return SocketIO(- app if app is not None else current_app,- cors_allowed_origins="*",- async_mode="threading",- path="/research/socket.io",- logger=False,- engineio_logger=False,- ping_timeout=20,- ping_interval=5,- )---def emit_socket_event(event, data, room=None):+ Singleton class for managing SocketIO connections and subscriptions."""- Emit a socket event to clients.-- Args:- event: The event name to emit- data: The data to send with the event- room: Optional room ID to send to specific client-- Returns:- bool: True if emission was successful, False otherwise- """- socketio = get_socketio()- try:- # If room is specified, only emit to that room- if room:- socketio.emit(event, data, room=room)- else:- # Otherwise broadcast to all- socketio.emit(event, data)- return True- except Exception as e:- logger.error(f"Error emitting socket event {event}: {str(e)}")- return False+ _instance = None++ def __new__(cls, *args: Any, app: Flask | None = None, **kwargs: Any):+ """+ Args:+ app: The Flask app to bind this service to. It must be specified+ the first time this is called and the singleton instance is+ created, but will be ignored after that.+ *args: Arguments to pass to the superclass's __new__ method.+ **kwargs: Keyword arguments to pass to the superclass's __new__ method.+ """+ if not cls._instance:+ if app is None:+ raise ValueError(+ "Flask app must be specified to create a SocketIOService instance."+ )+ cls._instance = super(SocketIOService, cls).__new__(cls, *args, **kwargs)+ cls._instance.__init_singleton(app)+ return cls._instance++ def __init_singleton(self, app: Flask) -> None:+ """+ Initializes the singleton instance.++ Args:+ app: The app to bind this service to.++ """+ self.__socketio = SocketIO(+ app,+ cors_allowed_origins="*",+ async_mode="threading",+ path="/research/socket.io",+ logger=False,+ engineio_logger=False,+ ping_timeout=20,+ ping_interval=5,+ )-def emit_to_subscribers(event_base, research_id, data):- """- Emit an event to all subscribers of a specific research.+ # Socket subscription tracking.+ self.__socket_subscriptions = {}++ # Register events.+ @self.__socketio.on("connect")+ def on_connect():+ self.__handle_connect(request)++ @self.__socketio.on("disconnect")+ def on_disconnect(reason: str):+ self.__handle_disconnect(request, reason)++ @self.__socketio.on("subscribe_to_research")+ def on_subscribe(data):+ globals_dict = get_globals()+ active_research = globals_dict.get("active_research", {})+ self.__handle_subscribe(data, request, active_research)++ @self.__socketio.on_error+ def on_error(e):+ return self.__handle_socket_error(e)++ @self.__socketio.on_error_default+ def on_default_error(e):+ return self.__handle_default_error(e)++ def emit_socket_event(self, event, data, room=None):+ """+ Emit a socket event to clients.++ Args:+ event: The event name to emit+ data: The data to send with the event+ room: Optional room ID to send to specific client++ Returns:+ bool: True if emission was successful, False otherwise+ """+ try:+ # If room is specified, only emit to that room+ if room:+ self.__socketio.emit(event, data, room=room)+ else:+ # Otherwise broadcast to all+ self.__socketio.emit(event, data)+ return True+ except Exception as e:+ logger.error(f"Error emitting socket event {event}: {str(e)}")+ return False++ def emit_to_subscribers(+ self, event_base, research_id, data, enable_logging: bool = True+ ):+ """+ Emit an event to all subscribers of a specific research.++ Args:+ event_base: Base event name (will be formatted with research_id)+ research_id: ID of the research+ data: The data to send with the event+ enable_logging: If set to false, this will disable all logging,+ which is useful if we are calling this inside of a logging+ handler.++ Returns:+ bool: True if emission was successful, False otherwise++ """+ try:+ # Emit to the general channel for the research+ full_event = f"{event_base}_{research_id}"+ self.__socketio.emit(full_event, data)++ # Emit to specific subscribers+ if (+ research_id in self.__socket_subscriptions+ and self.__socket_subscriptions[research_id]+ ):+ for sid in self.__socket_subscriptions[research_id]:+ try:+ self.__socketio.emit(full_event, data, room=sid)+ except Exception as sub_err:+ if enable_logging:+ logger.error(+ f"Error emitting to subscriber {sid}: {str(sub_err)}"+ )- Args:- event_base: Base event name (will be formatted with research_id)- research_id: ID of the research- data: The data to send with the event+ return True+ except Exception as e:+ if enable_logging:+ logger.exception(+ f"Error emitting to subscribers for research {research_id}: {str(e)}"+ )+ return False++ @staticmethod+ def __handle_connect(request):+ """Handle client connection"""+ logger.info(f"Client connected: {request.sid}")++ def __handle_disconnect(self, request, reason: str):+ """Handle client disconnection"""+ try:+ logger.info(f"Client {request.sid} disconnected because: {reason}")+ # Clean up subscriptions for this client+ if request.sid in self.__socket_subscriptions:+ del self.__socket_subscriptions[request.sid]+ logger.info(f"Removed subscription for client {request.sid}")+ except Exception as e:+ logger.error(f"Error handling disconnect: {e}")++ def __handle_subscribe(self, data, request, active_research=None):+ """Handle client subscription to research updates"""+ research_id = data.get("research_id")+ if research_id:+ # First check if this research is still active+ conn = get_db_connection()+ cursor = conn.cursor()+ cursor.execute(+ "SELECT status FROM research_history WHERE id = ?", (research_id,)+ )+ result = cursor.fetchone()+ conn.close()- Returns:- bool: True if emission was successful, False otherwise- """- socketio = get_socketio()- try:- # Emit to the general channel for the research- full_event = f"{event_base}_{research_id}"- socketio.emit(full_event, data)-- # Emit to specific subscribers- if research_id in socket_subscriptions and socket_subscriptions[research_id]:- for sid in socket_subscriptions[research_id]:- try:- socketio.emit(full_event, data, room=sid)- except Exception as sub_err:- logger.error(f"Error emitting to subscriber {sid}: {str(sub_err)}")-- return True- except Exception as e:- logger.exception(- f"Error emitting to subscribers for research {research_id}: {str(e)}"- )- return False+ # Only allow subscription to valid research+ if result:+ status = result[0]+ # Initialize subscription set if needed+ if research_id not in self.__socket_subscriptions:+ self.__socket_subscriptions[research_id] = set()-# Socket event handlers moved from app.py-def handle_connect(request):- """Handle client connection"""- logger.info(f"Client connected: {request.sid}")---def handle_disconnect(request, reason: str):- """Handle client disconnection"""- try:- logger.info(f"Client {request.sid} disconnected because: {reason}")- # Clean up subscriptions for this client- global socket_subscriptions- for research_id, subscribers in list(socket_subscriptions.items()):- if request.sid in subscribers:- subscribers.remove(request.sid)- if not subscribers:- socket_subscriptions.pop(research_id, None)- logger.info(f"Removed empty subscription for research {research_id}")- except Exception as e:- logger.error(f"Error handling disconnect: {e}")---def handle_subscribe(data, request, active_research=None):- """Handle client subscription to research updates"""- from datetime import datetime-- from ..models.database import get_db_connection-- research_id = data.get("research_id")- if research_id:- # First check if this research is still active- conn = get_db_connection()- cursor = conn.cursor()- cursor.execute(- "SELECT status FROM research_history WHERE id = ?", (research_id,)- )- result = cursor.fetchone()- conn.close()-- # Only allow subscription to valid research- if result:- status = result[0]-- # Initialize subscription set if needed- global socket_subscriptions- if research_id not in socket_subscriptions:- socket_subscriptions[research_id] = set()-- # Add this client to the subscribers- socket_subscriptions[research_id].add(request.sid)- logger.info(f"Client {request.sid} subscribed to research {research_id}")-- # Send current status immediately if available- if active_research and research_id in active_research:- progress = active_research[research_id]["progress"]- latest_log = (- active_research[research_id]["log"][-1]- if active_research[research_id]["log"]- else None+ # Add this client to the subscribers+ self.__socket_subscriptions[research_id].add(request.sid)+ logger.info(+ f"Client {request.sid} subscribed to research {research_id}")- if latest_log:- emit_socket_event(+ # Send current status immediately if available+ if active_research and research_id in active_research:+ progress = active_research[research_id]["progress"]+ latest_log = (+ active_research[research_id]["log"][-1]+ if active_research[research_id]["log"]+ else None+ )++ if latest_log:+ self.emit_socket_event(+ f"research_progress_{research_id}",+ {+ "progress": progress,+ "message": latest_log.get("message", "Processing..."),+ "status": "in_progress",+ "log_entry": latest_log,+ },+ room=request.sid,+ )+ elif status in ["completed", "failed", "suspended"]:+ # Send final status for completed research+ self.emit_socket_event(f"research_progress_{research_id}",{- "progress": progress,- "message": latest_log.get("message", "Processing..."),- "status": "in_progress",- "log_entry": latest_log,- },- room=request.sid,- )- elif status in ["completed", "failed", "suspended"]:- # Send final status for completed research- emit_socket_event(- f"research_progress_{research_id}",- {- "progress": 100 if status == "completed" else 0,- "message": (- "Research completed successfully"- if status == "completed"- else (- "Research failed"- if status == "failed"- else "Research was suspended"- )- ),- "status": status,- "log_entry": {- "time": datetime.utcnow().isoformat(),- "message": f"Research is {status}","progress": 100 if status == "completed" else 0,- "metadata": {- "phase": (- "complete" if status == "completed" else "error"+ "message": (+ "Research completed successfully"+ if status == "completed"+ else (+ "Research failed"+ if status == "failed"+ else "Research was suspended")+ ),+ "status": status,+ "log_entry": {+ "time": datetime.utcnow().isoformat(),+ "message": f"Research is {status}",+ "progress": 100 if status == "completed" else 0,+ "metadata": {+ "phase": (+ "complete" if status == "completed" else "error"+ )+ },},},- },+ room=request.sid,+ )+ else:+ # Research not found+ self.emit_socket_event(+ "error",+ {"message": f"Research ID {research_id} not found"},room=request.sid,)- else:- # Research not found- emit_socket_event(- "error",- {"message": f"Research ID {research_id} not found"},- room=request.sid,- )+ @staticmethod+ def __handle_socket_error(e):+ """Handle Socket.IO errors"""+ logger.error(f"Socket.IO error: {str(e)}")+ # Don't propagate exceptions to avoid crashing the server+ return False-def handle_socket_error(e):- """Handle Socket.IO errors"""- logger.error(f"Socket.IO error: {str(e)}")- # Don't propagate exceptions to avoid crashing the server- return False-+ @staticmethod+ def __handle_default_error(e):+ """Handle unhandled Socket.IO errors"""+ logger.error(f"Unhandled Socket.IO error: {str(e)}")+ # Don't propagate exceptions to avoid crashing the server+ return False-def handle_default_error(e):- """Handle unhandled Socket.IO errors"""- logger.error(f"Unhandled Socket.IO error: {str(e)}")- # Don't propagate exceptions to avoid crashing the server- return False+ def run(self, host: str, port: int, debug: bool = False) -> NoReturn:+ """+ Runs the SocketIO server.++ Args:+ host: The hostname to bind the server to.+ port: The port number to listen on.+ debug: Whether to run in debug mode. Defaults to False.++ """+ logger.info(f"Starting web server on {host}:{port} (debug: {debug})")+ self.__socketio.run(+ current_app,+ debug=debug,+ host=host,+ port=port,+ allow_unsafe_werkzeug=True,+ use_reloader=False,+ )