bethaus-app/search.py
2025-04-05 10:12:37 +00:00

63 lines
2.3 KiB
Python

import sqlite3
from flask import Flask, render_template, request, request, jsonify
import os
app = Flask(__name__)
SEARCH_DB_NAME = 'search.db'
search_db = sqlite3.connect(SEARCH_DB_NAME, check_same_thread=False)
search_db.row_factory = sqlite3.Row
def searchcommand():
query = request.form.get("query", "").strip()
include_transcript = request.form.get("includeTranscript") == "true" or request.form.get("includeTranscript") == "on"
words = [w for w in query.split() if w]
cursor = search_db.cursor()
if not include_transcript:
conditions = []
params = []
for word in words:
conditions.append("(relative_path LIKE ? OR filename LIKE ?)")
params.extend([f"%{word}%", f"%{word}%"])
sql = "SELECT * FROM files"
if conditions:
sql += " WHERE " + " AND ".join(conditions)
sql += " ORDER BY hitcount DESC"
cursor.execute(sql, params)
raw_results = cursor.fetchall()
results = [dict(row) for row in raw_results]
else:
# Advanced search: include transcript. Count transcript hits.
conditions = []
params = []
for word in words:
conditions.append("(relative_path LIKE ? OR filename LIKE ? OR transcript LIKE ?)")
params.extend([f"%{word}%", f"%{word}%", f"%{word}%"])
sql = "SELECT * FROM files"
if conditions:
sql += " WHERE " + " AND ".join(conditions)
cursor.execute(sql, params)
raw_results = cursor.fetchall()
results = []
for row in raw_results:
result = dict(row)
transcript = result.get("transcript") or ""
total_hits = sum(transcript.lower().count(word.lower()) for word in words)
result["transcript_hits"] = total_hits
result["transcript"] = None
results.append(result)
# Sort results so files with more transcript hits are on top.
results.sort(key=lambda x: x["transcript_hits"], reverse=True)
results = results[:100]
return jsonify(results=results)
def search():
title_short = os.environ.get('TITLE_SHORT', 'Default Title')
title_long = os.environ.get('TITLE_LONG', 'Default Title')
return render_template("search.html", title_short=title_short, title_long=title_long)