Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Add lightweight Docker image without PyTorch and improve text search fallback
Murtaza Nasira9f0f599ca24
diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.ymlindex 7966c3dc..2936b7a7 100644--- a/.github/workflows/docker-publish.yml+++ b/.github/workflows/docker-publish.yml@@ -58,7 +58,18 @@ jobs:type=shatype=raw,value=latest,enable=${{ github.event_name == 'workflow_dispatch' || github.event_name == 'release' || startsWith(github.ref, 'refs/tags/v') }}- # Build and push Docker image+ # Extract metadata for lite image+ - name: Extract Docker metadata (lite)+ id: meta-lite+ uses: docker/metadata-action@v4+ with:+ images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}+ tags: |+ type=raw,value=lite,enable=${{ github.event_name == 'workflow_dispatch' || github.event_name == 'release' || startsWith(github.ref, 'refs/tags/v') }}+ type=semver,pattern={{version}}-lite+ type=semver,pattern={{major}}.{{minor}}-lite++ # Build and push full Docker image- name: Build and push Docker imageid: build-and-pushuses: docker/build-push-action@v4@@ -72,3 +83,19 @@ jobs:cache-to: type=gha,mode=maxbuild-args: |PRODUCTION=1++ # Build and push lightweight Docker image (no PyTorch/sentence-transformers)+ - name: Build and push lite Docker image+ id: build-and-push-lite+ uses: docker/build-push-action@v4+ with:+ context: .+ platforms: linux/amd64,linux/arm64+ push: ${{ github.event_name != 'pull_request' }}+ tags: ${{ steps.meta-lite.outputs.tags }}+ labels: ${{ steps.meta-lite.outputs.labels }}+ cache-from: type=gha+ cache-to: type=gha,mode=max+ build-args: |+ PRODUCTION=1+ LIGHTWEIGHT=1diff --git a/.gitignore b/.gitignoreindex 339ff8de..10ad8750 100644--- a/.gitignore+++ b/.gitignore@@ -21,6 +21,7 @@ changes.txt!.github/CLA-SETUP.md!docs/**/*.mddocker-compose.dev.yml+docker-compose.lite.ymldocker-compose.postgres.yml.clinerulestemp/diff --git a/Dockerfile b/Dockerfileindex c8f287e0..a6c01e81 100644--- a/Dockerfile+++ b/Dockerfile@@ -2,6 +2,8 @@ FROM python:3.11-slim# Build argument to determine if this is a production buildARG PRODUCTION=0+# Set LIGHTWEIGHT=1 to skip PyTorch/sentence-transformers (~1.7GB smaller image)+ARG LIGHTWEIGHT=0WORKDIR /app@@ -12,8 +14,11 @@ RUN apt-get update && apt-get install -y --no-install-recommends \&& rm -rf /var/lib/apt/lists/*# Copy requirements first for better caching-COPY requirements.txt .-RUN pip install --no-cache-dir -r requirements.txt+COPY requirements.txt requirements-embeddings.txt ./+RUN pip install --no-cache-dir -r requirements.txt && \+ if [ "$LIGHTWEIGHT" = "0" ]; then \+ pip install --no-cache-dir -r requirements-embeddings.txt; \+ fi# Create directory structure for vendor filesRUN mkdir -p /app/static/vendordiff --git a/config/docker-compose.example.yml b/config/docker-compose.example.ymlindex 6d08e74c..3e238dd4 100644--- a/config/docker-compose.example.yml+++ b/config/docker-compose.example.yml@@ -1,5 +1,7 @@services:app:+ # Use 'lite' tag for a smaller image (~700MB vs ~4.4GB) without PyTorch+ # Semantic search in Inquire Mode falls back to text search; all other features work normallyimage: learnedmachine/speakr:latestcontainer_name: speakrrestart: unless-stoppeddiff --git a/requirements-embeddings.txt b/requirements-embeddings.txtnew file mode 100644index 00000000..81a9a1e2--- /dev/null+++ b/requirements-embeddings.txt@@ -0,0 +1,2 @@+sentence-transformers==2.7.0+huggingface-hub>=0.19.0diff --git a/requirements.txt b/requirements.txtindex 67720a90..af516800 100644--- a/requirements.txt+++ b/requirements.txt@@ -20,7 +20,5 @@ Babel==2.12.1bleach==6.1.0python-docx==1.1.0numpy==1.24.3-sentence-transformers==2.7.0scikit-learn==1.3.0-huggingface-hub>=0.19.0psycopg2-binary>=2.9.0diff --git a/src/api/inquire.py b/src/api/inquire.pyindex 9c1b20aa..2b510b0e 100644--- a/src/api/inquire.py+++ b/src/api/inquire.py@@ -16,7 +16,7 @@ from werkzeug.utils import secure_filenamefrom src.database import dbfrom src.models import *from src.utils import *-from src.services.embeddings import get_accessible_recording_ids, semantic_search_chunks+from src.services.embeddings import get_accessible_recording_ids, semantic_search_chunks, EMBEDDINGS_AVAILABLEfrom src.services.llm import call_llm_completion, call_chat_completion, process_streaming_with_thinking, client, chat_client, TokenBudgetExceeded# Create blueprint@@ -299,11 +299,12 @@ Use proper markdown formatting including headings (##), bold (**text**), bullet# Use captured user context for personalized search terms- enrichment_prompt = f"""You are a query enhancement assistant. Given a user's question about transcribed meetings/recordings, generate 3-5 alternative search terms or phrases that would help find relevant content in a semantic search system.+ if EMBEDDINGS_AVAILABLE:+ enrichment_prompt = f"""You are a query enhancement assistant. Given a user's question about transcribed meetings/recordings, generate 3-5 alternative search terms or phrases that would help find relevant content in a semantic search system.User context:- Name: {user_name}-- Title: {user_title}+- Title: {user_title}- Company: {user_company}User question: "{user_message}"@@ -321,6 +322,27 @@ Examples:- Use their job title and company context when relevantRespond with only a JSON array of strings: ["term1", "term2", "term3", ...]"""+ else:+ enrichment_prompt = f"""You are a keyword extraction assistant. Given a user's question about transcribed meetings/recordings, extract 3-5 essential keyword phrases for a basic text search (SQL LIKE matching, not semantic search).++User context:+- Name: {user_name}++User question: "{user_message}"++Rules:+- Return ONLY the key terms that would actually appear in a transcript — no filler words+- Each term should be 1-3 words maximum+- Replace pronouns like "me", "my", "I" with the user's name "{user_name}"+- Focus on proper nouns, topic-specific terms, and distinctive phrases+- Do NOT include common words like "meeting", "discussion", "plan", "talk" unless they are the actual topic++Examples:+- "what is up with Railroad Retirement" → ["Railroad Retirement", "railroad", "retirement"]+- "when did Beth mention the budget deadline" → ["Beth", "budget deadline", "budget"]+- "what did we discuss about AI foresight" → ["AI foresight", "{user_name}", "foresight"]++Respond with only a JSON array of strings: ["term1", "term2", ...]"""try:enrichment_response = call_llm_completion(diff --git a/src/services/embeddings.py b/src/services/embeddings.pyindex 26590a9f..fb42a374 100644--- a/src/services/embeddings.py+++ b/src/services/embeddings.py@@ -224,8 +224,8 @@ def basic_text_search_chunks(user_id, query, filters=None, top_k=5):if not accessible_recording_ids:return []- # Build base query for chunks from accessible recordings- chunks_query = TranscriptChunk.query.filter(+ # Build base query for chunks from accessible recordings with eager loading+ chunks_query = TranscriptChunk.query.options(joinedload(TranscriptChunk.recording)).filter(TranscriptChunk.recording_id.in_(accessible_recording_ids))@@ -263,23 +263,50 @@ def basic_text_search_chunks(user_id, query, filters=None, top_k=5):if filters.get('date_to'):chunks_query = chunks_query.filter(Recording.meeting_date <= filters['date_to'])- # Simple text search - split query into words and search for them- query_words = query.lower().split()+ # Text search - filter stop words and rank by match count+ stop_words = {'a', 'an', 'the', 'is', 'are', 'was', 'were', 'be', 'been',+ 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will',+ 'would', 'could', 'should', 'may', 'might', 'shall', 'can',+ 'to', 'of', 'in', 'for', 'on', 'with', 'at', 'by', 'from',+ 'up', 'about', 'into', 'through', 'during', 'before', 'after',+ 'and', 'but', 'or', 'nor', 'not', 'so', 'yet', 'both',+ 'it', 'its', 'this', 'that', 'these', 'those', 'what', 'which',+ 'who', 'whom', 'how', 'when', 'where', 'why',+ 'i', 'me', 'my', 'we', 'our', 'you', 'your', 'he', 'she',+ 'his', 'her', 'they', 'them', 'their'}++ query_words = [w for w in query.lower().split() if w not in stop_words and len(w) > 1]++ if not query_words:+ # If all words were stop words, fall back to using original query words+ query_words = [w for w in query.lower().split() if len(w) > 1]+if query_words:- # Create a filter that matches any of the query words in the content+ from sqlalchemy import or_, func, case, literal++ # Filter: match ANY keyword (OR) to get candidatestext_conditions = []for word in query_words:text_conditions.append(TranscriptChunk.content.ilike(f'%{word}%'))-- # Combine conditions with OR- from sqlalchemy import or_chunks_query = chunks_query.filter(or_(*text_conditions))-- # Get chunks and return with dummy similarity scores- chunks = chunks_query.limit(top_k).all()-- # Return chunks with dummy similarity scores (1.0 for found chunks)- return [(chunk, 1.0) for chunk in chunks]++ # Fetch more candidates than needed so we can rank them+ chunks = chunks_query.limit(top_k * 5).all()++ # Rank by how many query words each chunk matches+ scored_chunks = []+ for chunk in chunks:+ content_lower = chunk.content.lower()+ match_count = sum(1 for word in query_words if word in content_lower)+ score = match_count / len(query_words) # 0.0 to 1.0+ scored_chunks.append((chunk, score))++ # Sort by score descending, take top_k+ scored_chunks.sort(key=lambda x: x[1], reverse=True)+ return scored_chunks[:top_k]++ # No usable query words+ return []except Exception as e:current_app.logger.error(f"Error in basic text search: {e}")