Skip to content

~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.

Fix DB initialization.

Daniel Petti7e9ec1aa3961
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index 11a659a693..5007f2657c 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -1,7 +1,8 @@
-import os
import logging
-from dateutil import parser
-from src.local_deep_research.web.app_factory import create_app
+import os
+
+from ..config.config_files import settings
+from .app_factory import create_app
# Initialize logger
logger = logging.getLogger(__name__)
@@ -9,14 +10,12 @@ logger = logging.getLogger(__name__)
# Create the Flask app and SocketIO instance
app, socketio = create_app()
+
def main():
"""
Entry point for the web application when run as a command.
This function is needed for the package's entry point to work properly.
"""
- # Import configuration inside the function to avoid circular imports
- from src.local_deep_research.config.config_files import get_config_dir, settings
-
# Get web server settings with defaults
port = settings.web.port
host = settings.web.host
@@ -24,8 +23,6 @@ def main():
# Check for OpenAI availability but don't import it unless necessary
try:
- import os
-
api_key = os.environ.get("OPENAI_API_KEY")
if api_key:
try:
@@ -46,5 +43,6 @@ def main():
logger.info(f"Starting web server on {host}:{port} (debug: {debug})")
socketio.run(app, debug=debug, host=host, port=port, allow_unsafe_werkzeug=True)
+
if __name__ == "__main__":
- main()
\ No newline at end of file
+ main()
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 73d53f88a2..0292decbb6 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -1,25 +1,34 @@
-from importlib import resources as importlib_resources
import logging
import os
-import platform
-import traceback
+from importlib import resources as importlib_resources
-from flask import Blueprint, Flask, jsonify, make_response, send_from_directory, request, redirect, url_for
+from flask import (
+ Flask,
+ jsonify,
+ make_response,
+ redirect,
+ request,
+ send_from_directory,
+ url_for,
+)
from flask_socketio import SocketIO
+from .models.database import init_db
+
# Initialize logger
logger = logging.getLogger(__name__)
+
def create_app():
"""
Create and configure the Flask application.
-
+
Returns:
tuple: (app, socketio) - The configured Flask app and SocketIO instance
"""
# Configure logging
logging.basicConfig(level=logging.INFO)
-
+
try:
# Get directories based on package installation
PACKAGE_DIR = importlib_resources.files("src.local_deep_research") / "web"
@@ -39,17 +48,21 @@ def create_app():
static_folder=os.path.abspath("static"),
template_folder=os.path.abspath("templates"),
)
-
+
# App configuration
app.config["SECRET_KEY"] = "deep-research-secret-key"
-
+
# Database configuration
- db_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..', 'data', 'deep_research.db'))
+ db_path = os.path.abspath(
+ os.path.join(
+ os.path.dirname(__file__), "..", "..", "..", "data", "deep_research.db"
+ )
+ )
os.makedirs(os.path.dirname(db_path), exist_ok=True)
app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{db_path}"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SQLALCHEMY_ECHO"] = False
-
+
# Initialize extensions
socketio = SocketIO(
app,
@@ -61,31 +74,34 @@ def create_app():
ping_timeout=20,
ping_interval=5,
)
-
+
# Initialize database
create_database(app)
-
+ init_db()
+
# Register socket service
from .services.socket_service import set_socketio
+
set_socketio(socketio)
-
+
# Apply middleware
apply_middleware(app)
-
+
# Register blueprints
register_blueprints(app)
-
+
# Register error handlers
register_error_handlers(app)
-
+
# Register socket event handlers
register_socket_events(socketio)
-
+
return app, socketio
+
def apply_middleware(app):
"""Apply middleware to the Flask app."""
-
+
# Add Content Security Policy headers to allow Socket.IO to function
@app.after_request
def add_security_headers(response):
@@ -107,11 +123,13 @@ def apply_middleware(app):
# Add CORS headers for API requests
if request.path.startswith("/api/"):
response.headers["Access-Control-Allow-Origin"] = "*"
- response.headers["Access-Control-Allow-Methods"] = "GET, POST, DELETE, OPTIONS"
+ response.headers["Access-Control-Allow-Methods"] = (
+ "GET, POST, DELETE, OPTIONS"
+ )
response.headers["Access-Control-Allow-Headers"] = "Content-Type"
return response
-
+
# Add a middleware layer to handle abrupt disconnections
@app.before_request
def handle_websocket_requests():
@@ -124,73 +142,87 @@ def apply_middleware(app):
# Return empty response to prevent further processing
return "", 200
+
def register_blueprints(app):
"""Register blueprints with the Flask app."""
-
+
# Import blueprints
- from .routes.research_routes import research_bp
from .routes.history_routes import history_bp
- from .routes.settings_routes import settings_bp
+ from .routes.research_routes import research_bp
from .routes.settings_api import settings_api_bp
-
+ from .routes.settings_routes import settings_bp
+
# Register blueprints
app.register_blueprint(research_bp)
- app.register_blueprint(history_bp, url_prefix='/research/api')
+ app.register_blueprint(history_bp, url_prefix="/research/api")
app.register_blueprint(settings_bp)
- app.register_blueprint(settings_api_bp, url_prefix='/research/api')
-
+ app.register_blueprint(settings_api_bp, url_prefix="/research/api")
+
# Configure settings paths
# Import config inside the function to avoid circular dependencies
def configure_settings_routes():
try:
from ..config.config_files import SEARCH_ENGINES_FILE, get_config_dir
from .routes.settings_routes import set_config_paths
-
+
CONFIG_DIR = get_config_dir() / "config"
MAIN_CONFIG_FILE = CONFIG_DIR / "settings.toml"
LOCAL_COLLECTIONS_FILE = CONFIG_DIR / "local_collections.toml"
-
- set_config_paths(CONFIG_DIR, SEARCH_ENGINES_FILE, MAIN_CONFIG_FILE, LOCAL_COLLECTIONS_FILE)
+
+ set_config_paths(
+ CONFIG_DIR,
+ SEARCH_ENGINES_FILE,
+ MAIN_CONFIG_FILE,
+ LOCAL_COLLECTIONS_FILE,
+ )
except Exception as e:
logger.error(f"Error configuring settings routes: {e}")
-
+
# Call this after all blueprints are registered
configure_settings_routes()
-
+
# Add root route redirect
@app.route("/")
def root_index():
return redirect(url_for("research.index"))
-
+
# Add favicon route
@app.route("/favicon.ico")
def favicon():
return send_from_directory(
app.static_folder, "favicon.ico", mimetype="image/x-icon"
)
-
+
# Add static route at the app level for compatibility
@app.route("/static/<path:path>")
def app_serve_static(path):
return send_from_directory(app.static_folder, path)
+
def register_error_handlers(app):
"""Register error handlers with the Flask app."""
-
+
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({"error": "Not found"}), 404)
-
+
@app.errorhandler(500)
def server_error(error):
return make_response(jsonify({"error": "Server error"}), 500)
+
def register_socket_events(socketio):
"""Register Socket.IO event handlers."""
-
- from .services.socket_service import handle_connect, handle_disconnect, handle_subscribe, handle_socket_error, handle_default_error
+
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)
@@ -202,7 +234,7 @@ def register_socket_events(socketio):
@socketio.on("subscribe_to_research")
def on_subscribe(data):
globals_dict = get_globals()
- active_research = globals_dict.get('active_research', {})
+ active_research = globals_dict.get("active_research", {})
handle_subscribe(data, request, active_research)
@socketio.on_error
@@ -213,15 +245,16 @@ def register_socket_events(socketio):
def on_default_error(e):
return handle_default_error(e)
+
def create_database(app):
"""
Create the database and tables for the application.
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
-
- from .database.models import Base
+
from .database.migrations import run_migrations, setup_predefined_settings
+ from .database.models import Base
# Configure SQLite to use URI mode, which allows for relative file paths
engine = create_engine(
@@ -229,21 +262,21 @@ def create_database(app):
echo=app.config.get("SQLALCHEMY_ECHO", False),
connect_args={"check_same_thread": False},
)
-
+
app.engine = engine
-
+
# Create all tables
Base.metadata.create_all(engine)
-
+
# Configure session factory
session_factory = sessionmaker(bind=engine, autocommit=False, autoflush=False)
app.db_session = scoped_session(session_factory)
-
+
# Run migrations and setup predefined settings
run_migrations(engine, app.db_session)
setup_predefined_settings(app.db_session)
-
+
# Add teardown context
@app.teardown_appcontext
def remove_session(exception=None):
- app.db_session.remove()
\ No newline at end of file
+ app.db_session.remove()