Adam Cseresznye commited on
Commit
28ba0c9
·
1 Parent(s): 6885e0c

Initial deployment of Necthrall RAG application

Browse files
Files changed (9) hide show
  1. Dockerfile +47 -86
  2. agents/processing_agent.py +5 -0
  3. logo/favicon.png +3 -0
  4. main.py +39 -275
  5. requirements.txt +2 -2
  6. ui/__init__.py +6 -0
  7. ui/components.py +147 -0
  8. ui/pages.py +159 -0
  9. ui/styles.py +385 -0
Dockerfile CHANGED
@@ -1,110 +1,71 @@
1
  # ============================================================================
2
- # Necthrall - Production-Ready Multi-Stage Dockerfile for Heroku
3
  # ============================================================================
4
- # Optimized for Heroku Basic dyno (512MB RAM, 500MB slug limit)
 
 
5
  # ============================================================================
6
 
7
- # ============================================================================
8
- # STAGE 1: Builder - Install dependencies and prepare models
9
- # ============================================================================
10
- FROM python:3.11-slim AS builder
11
 
 
12
  ENV PYTHONDONTWRITEBYTECODE=1 \
13
  PYTHONUNBUFFERED=1 \
14
  PIP_NO_CACHE_DIR=1 \
15
- PIP_DISABLE_PIP_VERSION_CHECK=1
16
-
17
- RUN apt-get update && \
18
- apt-get install -y --no-install-recommends gcc g++ libffi-dev && \
19
- rm -rf /var/lib/apt/lists/*
20
-
21
- COPY requirements.txt /tmp/requirements.txt
22
-
23
- # --- 1. SETUP BUILD VENV (Heavy Tools) ---
24
- # We use this separate venv to run the ONNX export script with torch/transformers
25
- RUN python -m venv /opt/venv_build
26
- ENV PATH="/opt/venv_build/bin:$PATH"
27
-
28
- RUN echo "Installing CPU-only PyTorch for build..." && \
29
- pip install torch --index-url https://download.pytorch.org/whl/cpu
30
-
31
- RUN echo "Installing build dependencies..." && \
32
- pip install -r /tmp/requirements.txt && \
33
- pip install optimum[onnxruntime]
34
-
35
- # Create and populate model cache
36
- RUN mkdir -p /opt/onnx_model_cache
37
- COPY scripts/setup_onnx.py /tmp/setup_onnx.py
38
- WORKDIR /opt
39
- RUN echo "Exporting and quantizing ONNX model..." && \
40
- python /tmp/setup_onnx.py && \
41
- echo "ONNX model baked into image"
42
- RUN mv /opt/onnx_model_cache /opt/onnx_model_cache_final
43
-
44
- # --- 2. SETUP RUNTIME VENV (Lightweight App) ---
45
- # CRITICAL FIX: We create this at /opt/venv so paths match the final stage
46
- ENV PATH="/usr/local/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin"
47
- RUN python -m venv /opt/venv
48
- ENV PATH="/opt/venv/bin:$PATH"
49
-
50
- # Filter out heavy ML libs and install app dependencies
51
- RUN grep -vE "^torch|^transformers|^sentence-transformers|^optimum" /tmp/requirements.txt > /tmp/requirements_runtime.txt && \
52
- echo "Installing runtime requirements..." && \
53
- pip install -r /tmp/requirements_runtime.txt
54
-
55
- # Install lightweight inference engine
56
- RUN echo "Installing lightweight inference dependencies..." && \
57
- pip install onnxruntime tokenizers
58
-
59
- # ============================================================================
60
- # STAGE 2: Final - Minimal runtime image
61
- # ============================================================================
62
- FROM python:3.11-slim AS final
63
-
64
- ENV PYTHONDONTWRITEBYTECODE=1 \
65
- PYTHONUNBUFFERED=1 \
66
  OMP_NUM_THREADS=1 \
67
  MKL_NUM_THREADS=1 \
68
  TOKENIZERS_PARALLELISM=false
69
 
70
- # Setup Environment for Caches
71
- ENV TRANSFORMERS_CACHE=/app/.cache/huggingface \
72
- HF_HOME=/app/.cache/huggingface \
73
- SENTENCE_TRANSFORMERS_HOME=/app/.cache/sentence-transformers \
74
- TORCH_HOME=/app/.cache/torch
75
-
76
- WORKDIR /app
77
-
78
- # Install minimal runtime deps
79
  RUN apt-get update && \
80
- apt-get install -y --no-install-recommends ca-certificates && \
 
 
 
81
  apt-get clean && \
82
  rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
83
 
84
- # CRITICAL FIX: Copy from /opt/venv to /opt/venv (Matching Paths!)
85
- COPY --from=builder /opt/venv /opt/venv
86
- ENV PATH="/opt/venv/bin:$PATH"
 
 
 
87
 
88
- # Copy baked models
89
- COPY --from=builder /opt/onnx_model_cache_final /app/onnx_model_cache
 
 
 
 
 
90
 
91
- # Create directories
92
- RUN mkdir -p /app/.cache/huggingface /app/.cache/sentence-transformers /app/.cache/torch
 
 
93
 
94
- # Copy App
95
- COPY . /app
 
96
 
97
- # User Security
98
- RUN groupadd -g 1000 appuser && \
99
- useradd -u 1000 -g appuser -m -s /bin/bash appuser && \
100
- chown -R appuser:appuser /app
101
 
102
- USER appuser
 
 
 
 
103
 
104
- # Sanity Check
105
- RUN python -c "import onnxruntime; print(f'Runtime Ready: {onnxruntime.__version__}')"
106
 
107
- EXPOSE $PORT
 
 
 
108
 
109
- # Start
110
- CMD ["sh", "-c", "python -c 'import gc; gc.set_threshold(50, 5, 5);' && uvicorn main:app --host 0.0.0.0 --port ${PORT:-8000} --workers 1 --timeout-keep-alive 30"]
 
1
  # ============================================================================
2
+ # Necthrall - Optimized Dockerfile for Hugging Face Spaces (Docker SDK)
3
  # ============================================================================
4
+ # - Base: python:3.11-slim
5
+ # - Pre-downloads sentence-transformers/all-MiniLM-L6-v2
6
+ # - Runs as non-root user (UID 1000) on port 7860
7
  # ============================================================================
8
 
9
+ FROM python:3.11-slim
 
 
 
10
 
11
+ # Environment variables for Python and ML optimization
12
  ENV PYTHONDONTWRITEBYTECODE=1 \
13
  PYTHONUNBUFFERED=1 \
14
  PIP_NO_CACHE_DIR=1 \
15
+ PIP_DISABLE_PIP_VERSION_CHECK=1 \
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  OMP_NUM_THREADS=1 \
17
  MKL_NUM_THREADS=1 \
18
  TOKENIZERS_PARALLELISM=false
19
 
20
+ # ============================================================================
21
+ # STEP 1: Install system dependencies
22
+ # ============================================================================
 
 
 
 
 
 
23
  RUN apt-get update && \
24
+ apt-get install -y --no-install-recommends \
25
+ gcc \
26
+ g++ \
27
+ ca-certificates && \
28
  apt-get clean && \
29
  rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
30
 
31
+ # ============================================================================
32
+ # STEP 2: Install Python dependencies
33
+ # ============================================================================
34
+ COPY requirements.txt /tmp/requirements.txt
35
+ RUN pip install --no-cache-dir -r /tmp/requirements.txt && \
36
+ rm /tmp/requirements.txt
37
 
38
+ # ============================================================================
39
+ # STEP 3: Pre-download embedding model (cached in image layer)
40
+ # ============================================================================
41
+ # Download only the MiniLM model for chunk embedding
42
+ RUN python -c "from sentence_transformers import SentenceTransformer; \
43
+ model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2'); \
44
+ print('Model downloaded successfully:', model)"
45
 
46
+ # ============================================================================
47
+ # STEP 4: Create non-root user (HF Spaces requirement: UID 1000)
48
+ # ============================================================================
49
+ RUN useradd -m -u 1000 user
50
 
51
+ # Set home and working directory
52
+ ENV HOME=/home/user \
53
+ PATH=/home/user/.local/bin:$PATH
54
 
55
+ WORKDIR $HOME/app
 
 
 
56
 
57
+ # ============================================================================
58
+ # STEP 5: Copy application code
59
+ # ============================================================================
60
+ # Copy with ownership set to user
61
+ COPY --chown=user:user . $HOME/app
62
 
63
+ # Switch to non-root user
64
+ USER user
65
 
66
+ # ============================================================================
67
+ # STEP 6: Expose port and run application
68
+ # ============================================================================
69
+ EXPOSE 7860
70
 
71
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
 
agents/processing_agent.py CHANGED
@@ -85,6 +85,9 @@ class ProcessingAgent:
85
  influential = passage.get(
86
  "influentialCitationCount", passage.get("influential_citation_count", 0)
87
  )
 
 
 
88
  text = passage.get("text", "") or ""
89
 
90
  if not text.strip():
@@ -152,6 +155,8 @@ class ProcessingAgent:
152
  node.metadata["venue"] = venue
153
  if influential is not None:
154
  node.metadata["influential_citation_count"] = influential
 
 
155
 
156
  all_chunks.append(node)
157
  paper_chunk_count += 1
 
85
  influential = passage.get(
86
  "influentialCitationCount", passage.get("influential_citation_count", 0)
87
  )
88
+ # Extract PDF URL from openAccessPdf object
89
+ oa_pdf = passage.get("openAccessPdf")
90
+ pdf_url = oa_pdf.get("url") if oa_pdf and isinstance(oa_pdf, dict) else None
91
  text = passage.get("text", "") or ""
92
 
93
  if not text.strip():
 
155
  node.metadata["venue"] = venue
156
  if influential is not None:
157
  node.metadata["influential_citation_count"] = influential
158
+ if pdf_url:
159
+ node.metadata["pdf_url"] = pdf_url
160
 
161
  all_chunks.append(node)
162
  paper_chunk_count += 1
logo/favicon.png ADDED

Git LFS Details

  • SHA256: 5c256423075f41c0952042206026dcea36046c1dc714a281521d9304b317e067
  • Pointer size: 132 Bytes
  • Size of remote file: 4.29 MB
main.py CHANGED
@@ -1,6 +1,6 @@
1
- """Minimal FastAPI app for Necthrall Lite MVP.
2
 
3
- Exposes a /health endpoint for readiness checks.
4
  """
5
 
6
  import os
@@ -28,31 +28,16 @@ if os.name == "nt":
28
  except ImportError:
29
  pass
30
 
31
- from fastapi import FastAPI, HTTPException, BackgroundTasks
32
  from fastapi.middleware.cors import CORSMiddleware
33
- from pydantic import BaseModel, Field
34
  from loguru import logger
35
  from datetime import datetime
36
- import time
37
- import numpy as np
38
- from services.job_manager import job_manager
39
- from services.query_service import (
40
- QueryOptimizationError,
41
- SemanticScholarError,
42
- QualityGateError,
43
- RankingError,
44
- AcquisitionError,
45
- ProcessingError,
46
- RetrievalError,
47
- RerankingError,
48
- SynthesisError,
49
- VerificationError,
50
- )
51
 
52
  # Configure loguru with immediate flush for Windows compatibility
53
  logger.remove()
54
  logger.add(
55
- sys.stderr, # Use stderr for immediate output (not buffered like stdout)
56
  format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan> - <level>{message}</level>",
57
  level="INFO",
58
  )
@@ -60,108 +45,31 @@ logger.add(
60
  app = FastAPI(
61
  title="Necthrall API",
62
  description="AI-powered scientific research assistant",
63
- version="3.0.0-mvp",
64
  )
65
 
66
- # Configure CORS (permissive for development)
67
  app.add_middleware(
68
  CORSMiddleware,
69
- allow_origins=["*"], # Will tighten in Week 4
70
  allow_credentials=True,
71
  allow_methods=["*"],
72
  allow_headers=["*"],
73
  )
74
 
75
 
76
- # Pydantic models
77
- class QueryRequest(BaseModel):
78
- """Request model for /query endpoint.
79
-
80
- Attributes:
81
- query: The user's scientific research question.
82
- """
83
-
84
- query: str = Field(
85
- ...,
86
- min_length=1,
87
- max_length=500,
88
- description="User query string",
89
- json_schema_extra={
90
- "example": "What are the cardiovascular effects of intermittent fasting?"
91
- },
92
- )
93
-
94
-
95
- class CitationItem(BaseModel):
96
- """A single citation with text content and metadata for frontend display.
97
-
98
- Attributes:
99
- id: 1-based citation index corresponding to [N] in the answer.
100
- text: The passage text content.
101
- metadata: Additional metadata (paper_id, paper_title, section, score, etc.).
102
- """
103
-
104
- id: int = Field(
105
- ..., description="1-based citation index corresponding to [N] in the answer"
106
- )
107
- text: str = Field(..., description="The passage text content")
108
- metadata: dict = Field(
109
- default_factory=dict,
110
- description="Additional metadata (paper_id, paper_title, section, score)",
111
- )
112
-
113
-
114
- class QueryResponse(BaseModel):
115
- """Response model for /query endpoint.
116
-
117
- This is the CRITICAL schema for the Frontend (Week 4).
118
-
119
- Attributes:
120
- answer: The synthesized answer text with inline [N] citations.
121
- citations: List of citation items for frontend modal display.
122
- finalists: List of papers found during search.
123
- execution_time: Total pipeline execution time in seconds.
124
- timing_breakdown: Per-stage timing in seconds.
125
- """
126
-
127
- answer: str = Field(
128
- ...,
129
- description="The synthesized answer text with inline [N] citations",
130
- )
131
- citations: list[CitationItem] = Field(
132
- default_factory=list,
133
- description="List of citations with id, text, and metadata for frontend modal",
134
- )
135
- finalists: list = Field(
136
- default_factory=list,
137
- description="List of papers found during search",
138
- )
139
- execution_time: float = Field(
140
- ...,
141
- description="Total pipeline execution time in seconds",
142
- )
143
- timing_breakdown: dict = Field(
144
- default_factory=dict,
145
- description="Per-stage timing breakdown in seconds",
146
- )
147
-
148
-
149
  @app.on_event("startup")
150
  async def startup_event():
151
- """Validate configuration at startup
152
-
153
- Week 2: Will add local embedding model for passage-level chunking.
154
- """
155
  try:
156
- import config # Triggers validation
157
 
158
- # Initialize query service first (no embedding model needed for Week 1 behavior)
159
  from services.query_service import QueryService
160
 
161
  app.state.query_service = QueryService()
162
- logger.info("🚀 Query service initialized (Week 1 pipeline ready)")
163
 
164
- # Initialize the local embedding model for Week 2+ pipelines
165
  embedding_loaded = False
166
  try:
167
  from config.embedding_config import init_embedding
@@ -170,34 +78,19 @@ async def startup_event():
170
  embedding_loaded = True
171
  logger.info("✅ Embedding model loaded successfully")
172
  except ImportError as e:
173
- logger.warning(
174
- "⚠️ Embedding config module not found: {}. Week 1 pipeline still available.",
175
- str(e),
176
- )
177
  except RuntimeError as e:
178
- logger.warning(
179
- "⚠️ ONNX model file missing or runtime error: {}. Week 1 pipeline still available.",
180
- str(e),
181
- )
182
  except Exception:
183
- logger.exception(
184
- "⚠️ Embedding model failed to initialize; continuing without it (Week 1 pipeline available)"
185
- )
186
 
187
- # Inject embedding model into QueryService if successfully loaded
188
  if embedding_loaded and hasattr(app.state, "embedding_model"):
189
  try:
190
  app.state.query_service.embedding_model = app.state.embedding_model
191
  logger.info("✅ Embedding model injected into QueryService")
192
  except Exception as e:
193
- logger.warning(
194
- "❌ Failed to inject embedding model into QueryService: {}. Week 1 pipeline still available.",
195
- str(e),
196
- )
197
- elif not embedding_loaded:
198
- logger.info(
199
- "ℹ️ QueryService running without embedding model (Week 1 pipeline mode)"
200
- )
201
 
202
  logger.info("✅ Application startup successful")
203
  logger.info(f"Query optimization model: {config.QUERY_OPTIMIZATION_MODEL}")
@@ -207,165 +100,36 @@ async def startup_event():
207
  sys.exit(1)
208
 
209
 
210
- @app.get("/")
211
- async def root():
212
- """Root endpoint with API documentation link"""
213
- return {
214
- "message": "Necthrall API v3.0.0",
215
- "docs": "/docs",
216
- "health": "/health",
217
- }
218
-
219
-
220
  @app.get("/health")
221
  async def health_check():
222
- """Health check endpoint"""
223
- try:
224
- return {
225
- "status": "healthy",
226
- "timestamp": datetime.now().isoformat(),
227
- "version": "3.0.0-mvp",
228
- }
229
- except Exception as e:
230
- logger.exception("Health check failed")
231
- return {
232
- "status": "unhealthy",
233
- "error": str(e),
234
- "timestamp": datetime.now().isoformat(),
235
- }
236
-
237
-
238
- @app.post("/query")
239
- async def query_endpoint(request: QueryRequest, background_tasks: BackgroundTasks):
240
- """Submit a query for asynchronous processing.
241
-
242
- **Pipeline Stages:**
243
- - Week 1 (1-4): query_optimization → semantic_scholar_search → quality_gate → composite_scoring
244
- - Week 2 (5-8): pdf_acquisition → processing → hybrid_retrieval → cross_encoder_reranking
245
- - Week 3 (9-10): synthesis → citation_verification
246
-
247
- **Returns immediately with:**
248
- - `task_id`: UUID to poll for results
249
- - `status`: "pending"
250
-
251
- **Poll GET /jobs/{task_id} for results.**
252
- """
253
- # Create a new job
254
- job_id = job_manager.create_job()
255
- logger.info(f"📋 Created job {job_id} for query: {request.query[:100]}...")
256
-
257
- # Schedule background processing
258
- background_tasks.add_task(
259
- run_query_background,
260
- job_id=job_id,
261
- query=request.query,
262
- query_service=app.state.query_service,
263
- )
264
-
265
- return {"task_id": job_id, "status": "pending"}
266
-
267
-
268
- async def run_query_background(job_id: str, query: str, query_service) -> None:
269
- """Background wrapper that runs the query pipeline and updates the job manager.
270
-
271
- Args:
272
- job_id: The UUID of the job to update.
273
- query: The user's query string.
274
- query_service: The QueryService instance.
275
- """
276
- try:
277
- job_manager.update_job(job_id, "processing")
278
- logger.info(f"🔄 Processing job {job_id}...")
279
-
280
- # Run the actual pipeline
281
- result = await query_service.process_query(query)
282
-
283
- # Check if pipeline succeeded
284
- if not result.success:
285
- error_msg = f"Pipeline failed at stage '{result.error_stage}': {result.error_message}"
286
- logger.error(f"❌ Job {job_id}: {error_msg}")
287
- job_manager.update_job(job_id, "failed", error=error_msg)
288
- return
289
-
290
- # Transform passages to citations with id, text, and metadata
291
- citations = []
292
- for idx, passage in enumerate(result.passages):
293
- try:
294
- # Extract text content
295
- text = (
296
- passage.node.get_content()
297
- if hasattr(passage.node, "get_content")
298
- else str(passage.node)
299
- )
300
-
301
- # Extract metadata
302
- metadata = (
303
- passage.node.metadata.copy()
304
- if hasattr(passage.node, "metadata") and passage.node.metadata
305
- else {}
306
- )
307
-
308
- # Add score to metadata for frontend use
309
- metadata["score"] = passage.score
310
-
311
- citation_item = {
312
- "id": idx + 1, # 1-based index to match [N] citations
313
- "text": text,
314
- "metadata": metadata,
315
- }
316
- citations.append(citation_item)
317
- except Exception as e:
318
- logger.warning(f"Failed to serialize passage {idx}: {e}")
319
- continue
320
-
321
- # Get the answer (fallback to empty string if None)
322
- answer = (
323
- result.answer or "No answer could be generated from the available sources."
324
- )
325
-
326
- # Build the response
327
- response = {
328
- "answer": answer,
329
- "citations": citations,
330
- "finalists": result.finalists,
331
- "execution_time": result.execution_time,
332
- "timing_breakdown": result.timing_breakdown,
333
- }
334
 
335
- job_manager.update_job(job_id, "completed", result=response)
336
- logger.info(
337
- f"✅ Job {job_id} completed: {len(citations)} citations, "
338
- f"{len(result.finalists)} finalists, {result.execution_time:.2f}s"
339
- )
340
 
341
- except Exception as e:
342
- error_msg = f"Unexpected error: {str(e)}"
343
- logger.exception(f"❌ Job {job_id} failed: {error_msg}")
344
- job_manager.update_job(job_id, "failed", error=error_msg)
345
 
 
346
 
347
- @app.get("/jobs/{task_id}")
348
- async def get_job_status(task_id: str):
349
- """Poll for job status and results.
350
 
351
- **Returns:**
352
- - `id`: The job UUID
353
- - `status`: "pending", "processing", "completed", or "failed"
354
- - `created_at`: Timestamp when job was created
355
- - `result`: The QueryResponse object (when status is "completed")
356
- - `error`: Error message (when status is "failed")
357
- """
358
- job = job_manager.get_job(task_id)
359
- if job is None:
360
- raise HTTPException(status_code=404, detail=f"Job {task_id} not found")
361
- return job
362
 
363
 
364
  if __name__ == "__main__":
365
- # Keep local run simple; uvicorn invocation is optional in dev
366
- try:
367
- import uvicorn
368
 
369
- uvicorn.run("main:app", host="127.0.0.1", port=8000, log_level="info")
370
- except Exception:
371
- logger.debug("uvicorn not available or failed to start (fine for tests)")
 
1
+ """Necthrall - AI-Powered Scientific Research Assistant.
2
 
3
+ FastAPI + NiceGUI integrated application for research paper analysis.
4
  """
5
 
6
  import os
 
28
  except ImportError:
29
  pass
30
 
31
+ from fastapi import FastAPI
32
  from fastapi.middleware.cors import CORSMiddleware
 
33
  from loguru import logger
34
  from datetime import datetime
35
+ from nicegui import ui
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  # Configure loguru with immediate flush for Windows compatibility
38
  logger.remove()
39
  logger.add(
40
+ sys.stderr,
41
  format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan> - <level>{message}</level>",
42
  level="INFO",
43
  )
 
45
  app = FastAPI(
46
  title="Necthrall API",
47
  description="AI-powered scientific research assistant",
48
+ version="3.0.0",
49
  )
50
 
51
+ # Configure CORS
52
  app.add_middleware(
53
  CORSMiddleware,
54
+ allow_origins=["*"],
55
  allow_credentials=True,
56
  allow_methods=["*"],
57
  allow_headers=["*"],
58
  )
59
 
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  @app.on_event("startup")
62
  async def startup_event():
63
+ """Initialize query service at startup."""
 
 
 
64
  try:
65
+ import config
66
 
 
67
  from services.query_service import QueryService
68
 
69
  app.state.query_service = QueryService()
70
+ logger.info("🚀 Query service initialized")
71
 
72
+ # Initialize embedding model if available
73
  embedding_loaded = False
74
  try:
75
  from config.embedding_config import init_embedding
 
78
  embedding_loaded = True
79
  logger.info("✅ Embedding model loaded successfully")
80
  except ImportError as e:
81
+ logger.warning(f"⚠️ Embedding config module not found: {e}")
 
 
 
82
  except RuntimeError as e:
83
+ logger.warning(f"⚠️ ONNX model file missing: {e}")
 
 
 
84
  except Exception:
85
+ logger.exception("⚠️ Embedding model failed to initialize")
 
 
86
 
87
+ # Inject embedding model into QueryService if loaded
88
  if embedding_loaded and hasattr(app.state, "embedding_model"):
89
  try:
90
  app.state.query_service.embedding_model = app.state.embedding_model
91
  logger.info("✅ Embedding model injected into QueryService")
92
  except Exception as e:
93
+ logger.warning(f"❌ Failed to inject embedding model: {e}")
 
 
 
 
 
 
 
94
 
95
  logger.info("✅ Application startup successful")
96
  logger.info(f"Query optimization model: {config.QUERY_OPTIMIZATION_MODEL}")
 
100
  sys.exit(1)
101
 
102
 
 
 
 
 
 
 
 
 
 
 
103
  @app.get("/health")
104
  async def health_check():
105
+ """Health check endpoint."""
106
+ return {
107
+ "status": "healthy",
108
+ "timestamp": datetime.now().isoformat(),
109
+ "version": "3.0.0",
110
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
 
 
 
 
 
112
 
113
+ # =============================================================================
114
+ # NiceGUI Frontend
115
+ # =============================================================================
 
116
 
117
+ from ui.pages import init_ui
118
 
119
+ # Initialize UI with FastAPI app reference
120
+ init_ui(app)
 
121
 
122
+ # Mount NiceGUI with FastAPI
123
+ ui.run_with(
124
+ app,
125
+ title="Nechtrall",
126
+ favicon="logo/favicon.png",
127
+ dark=False,
128
+ storage_secret="necthrall-secret-key",
129
+ )
 
 
 
130
 
131
 
132
  if __name__ == "__main__":
133
+ import uvicorn
 
 
134
 
135
+ uvicorn.run("main:app", host="0.0.0.0", port=7860, log_level="info")
 
 
requirements.txt CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:ca2a51dc0f915abc6273d15e591e7c2955810d70e9ccda707ec603bd11958c81
3
- size 378
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07e4d5992f09ca129a02b47b398f4222ca408ddb9cfbd50b20c83c9195f05c35
3
+ size 428
ui/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """NiceGUI frontend components for Necthrall."""
2
+
3
+ from ui.pages import init_ui
4
+ from ui.styles import CUSTOM_CSS
5
+
6
+ __all__ = ["init_ui", "CUSTOM_CSS"]
ui/components.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reusable UI components for Necthrall."""
2
+
3
+ from nicegui import ui
4
+ from loguru import logger
5
+
6
+
7
+ import re
8
+
9
+
10
+ def _clean_markdown(text: str) -> str:
11
+ """Clean up markdown formatting for display.
12
+
13
+ Removes list markers while preserving **bold** formatting.
14
+ """
15
+ # Remove "* " but not "**" (bold) - match single * followed by space, not preceded by *
16
+ text = re.sub(r"(?<!\*)\* (?!\*)", "", text)
17
+ return text
18
+
19
+
20
+ def render_loading():
21
+ """Render the loading spinner with status text."""
22
+ with ui.column().classes("loading-container w-full") as container:
23
+ ui.spinner("dots", size="xl", color="#f97316")
24
+ ui.label("Analyzing Research...").classes("loading-text")
25
+ ui.label("Searching papers, extracting insights, synthesizing answer").classes(
26
+ "text-slate-400 text-sm mt-2"
27
+ )
28
+ return container
29
+
30
+
31
+ def render_answer(result):
32
+ """Render the answer section.
33
+
34
+ Args:
35
+ result: PipelineResult object with answer, execution_time, finalists, passages
36
+ """
37
+ with ui.column().classes("answer-section w-full"):
38
+ # Stats row
39
+ with ui.row().classes("items-center gap-3 mb-4"):
40
+ with ui.row().classes("gap-2"):
41
+ ui.label(f"⏱️ {result.execution_time:.1f}s").classes("stats-badge")
42
+ ui.label(f"📄 {len(result.finalists)} papers analyzed").classes(
43
+ "stats-badge"
44
+ )
45
+ ui.label(f"📝 {len(result.passages)} sources cited").classes(
46
+ "stats-badge"
47
+ )
48
+
49
+ # Answer text - clean up markdown and display
50
+ answer_text = _clean_markdown(result.answer)
51
+ ui.markdown(answer_text).classes("answer-text")
52
+
53
+
54
+ def render_sources(passages):
55
+ """Render the sources section as cards.
56
+
57
+ Args:
58
+ passages: List of passage objects with node and score attributes
59
+ """
60
+ if not passages:
61
+ return
62
+
63
+ with ui.column().classes("sources-section w-full"):
64
+ ui.label("SOURCES CITED").classes("sources-title")
65
+
66
+ for idx, passage in enumerate(passages):
67
+ try:
68
+ # Extract passage info
69
+ text = (
70
+ passage.node.get_content()
71
+ if hasattr(passage.node, "get_content")
72
+ else str(passage.node)
73
+ )
74
+ metadata = (
75
+ passage.node.metadata if hasattr(passage.node, "metadata") else {}
76
+ )
77
+ paper_title = metadata.get("paper_title", "Unknown Source")
78
+ paper_id = metadata.get("paper_id", "")
79
+ section = metadata.get("section", "")
80
+ # Try to get PDF URL from metadata
81
+ pdf_url = metadata.get("pdf_url", "") or metadata.get("url", "")
82
+
83
+ with ui.expansion().classes("source-card").props("dense") as expansion:
84
+ # Header slot for title
85
+ with expansion.add_slot("header"):
86
+ with ui.column().classes("w-full"):
87
+ # Title
88
+ ui.label(paper_title).classes("source-title")
89
+
90
+ # Meta info
91
+ meta_parts = []
92
+ if section:
93
+ meta_parts.append(section)
94
+ meta_parts.append(f"Citation [{idx + 1}]")
95
+ ui.label(" • ".join(meta_parts)).classes("source-meta")
96
+
97
+ # PDF link if available
98
+ if pdf_url:
99
+ with ui.row().classes("items-center mt-2"):
100
+ with (
101
+ ui.element("a")
102
+ .props(f'href="{pdf_url}" target="_blank"')
103
+ .classes("source-link-btn")
104
+ ):
105
+ ui.label("📄 Open Access PDF")
106
+ else:
107
+ with ui.row().classes("items-center mt-2"):
108
+ ui.html(
109
+ '<span class="source-link-badge">📄 PDF not available</span>',
110
+ sanitize=False,
111
+ )
112
+
113
+ # Expanded content - full passage
114
+ with ui.column().classes("passage-content"):
115
+ ui.label(text).classes("source-snippet")
116
+
117
+ except Exception as e:
118
+ logger.warning(f"Failed to render passage {idx}: {e}")
119
+ continue
120
+
121
+
122
+ def render_error(error_message: str, error_stage: str = None):
123
+ """Render an error card.
124
+
125
+ Args:
126
+ error_message: The error message to display
127
+ error_stage: Optional stage where the error occurred
128
+ """
129
+ with ui.column().classes("error-card w-full"):
130
+ with ui.row().classes("items-center gap-3"):
131
+ ui.icon("error_outline", color="#ef4444", size="sm")
132
+ ui.label("Analysis Failed").classes("text-lg font-semibold text-red-600")
133
+ ui.label(error_message).classes("text-red-500 mt-2")
134
+ if error_stage:
135
+ ui.label(f"Stage: {error_stage}").classes("text-red-400 text-sm mt-1")
136
+
137
+
138
+ def render_exception_error(exception: Exception):
139
+ """Render an error card for an exception.
140
+
141
+ Args:
142
+ exception: The exception that was raised
143
+ """
144
+ with ui.column().classes("error-card w-full"):
145
+ ui.icon("error_outline", color="#ef4444", size="sm")
146
+ ui.label("Error").classes("text-lg font-semibold text-red-600")
147
+ ui.label(str(exception)).classes("text-red-500 mt-2")
ui/pages.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Page definitions for the Necthrall UI."""
2
+
3
+ from pathlib import Path
4
+ from nicegui import ui, context, app
5
+ from loguru import logger
6
+
7
+ from ui.styles import CUSTOM_CSS
8
+ from ui.components import (
9
+ render_loading,
10
+ render_answer,
11
+ render_sources,
12
+ render_error,
13
+ render_exception_error,
14
+ )
15
+
16
+ # Path to logo directory
17
+ LOGO_DIR = (
18
+ Path(__file__).resolve().parent.parent.joinpath("logo").joinpath("nechtrall.png")
19
+ )
20
+
21
+
22
+ def init_ui(fastapi_app):
23
+ """Initialize the NiceGUI frontend.
24
+
25
+ Args:
26
+ fastapi_app: The FastAPI application instance with query_service in state
27
+ """
28
+
29
+ @ui.page("/")
30
+ async def index_page():
31
+ # Inject custom CSS
32
+ ui.add_head_html(f"<style>{CUSTOM_CSS}</style>")
33
+
34
+ # Get client reference for connection checking
35
+ client = context.client
36
+
37
+ # State containers
38
+ results_container = None
39
+
40
+ def is_connected() -> bool:
41
+ """Check if the client is still connected."""
42
+ try:
43
+ return client.has_socket_connection
44
+ except Exception:
45
+ return False
46
+
47
+ async def handle_search():
48
+ nonlocal results_container
49
+ query_text = search_input.value.strip()
50
+
51
+ if not query_text:
52
+ ui.notify("Please enter a research question", type="warning")
53
+ return
54
+
55
+ # Clear previous results
56
+ if results_container and is_connected():
57
+ results_container.clear()
58
+
59
+ # Show loading
60
+ if not is_connected():
61
+ return
62
+ with results_container:
63
+ render_loading()
64
+
65
+ try:
66
+ # Call the query service
67
+ result = await fastapi_app.state.query_service.process_query(query_text)
68
+
69
+ # Check if client is still connected before updating UI
70
+ if not is_connected():
71
+ logger.info(
72
+ "Client disconnected during query processing, skipping UI update"
73
+ )
74
+ return
75
+
76
+ # Clear loading
77
+ results_container.clear()
78
+
79
+ with results_container:
80
+ if result.success and result.answer:
81
+ # Success - show answer and sources
82
+ render_answer(result)
83
+ render_sources(result.passages)
84
+ else:
85
+ # Failed
86
+ error_msg = (
87
+ result.error_message or "An unexpected error occurred"
88
+ )
89
+ render_error(error_msg, result.error_stage)
90
+
91
+ except Exception as e:
92
+ logger.exception("Query processing failed")
93
+ # Only update UI if client is still connected
94
+ if not is_connected():
95
+ logger.info("Client disconnected, skipping error UI update")
96
+ return
97
+ try:
98
+ results_container.clear()
99
+ with results_container:
100
+ render_exception_error(e)
101
+ except RuntimeError:
102
+ # Client was deleted, silently ignore
103
+ pass
104
+
105
+ # =====================================================================
106
+ # HEADER
107
+ # =====================================================================
108
+ with ui.row().classes("header-container items-center justify-center"):
109
+ # Logo and brand
110
+ with ui.row().classes("items-center gap-1"):
111
+
112
+ ui.image(LOGO_DIR).classes("w-20 h-20 object-contain").props(
113
+ "no-spinner"
114
+ )
115
+ ui.label("Nechtrall").classes("text-4xl font-bold text-slate-800")
116
+
117
+ # =====================================================================
118
+ # MAIN CONTENT
119
+ # =====================================================================
120
+ with ui.column().classes("w-full items-center px-4 py-8"):
121
+ # Search container
122
+ with ui.column().classes("search-container"):
123
+ # Search wrapper
124
+ with ui.row().classes("search-wrapper w-full items-center gap-2"):
125
+ ui.icon("search", size="sm").classes("text-slate-400 ml-3")
126
+ search_input = (
127
+ ui.input(
128
+ placeholder="cardiovascular effects of intermittent fasting"
129
+ )
130
+ .classes("search-input flex-grow")
131
+ .props("borderless dense")
132
+ )
133
+ search_input.on("keydown.enter", handle_search)
134
+
135
+ ui.button("Search", on_click=handle_search).classes(
136
+ "search-btn mr-1"
137
+ )
138
+
139
+ # Example queries
140
+ with ui.row().classes(
141
+ "example-queries gap-2 mt-4 flex-wrap justify-center"
142
+ ):
143
+ ui.label("Try:").classes("text-slate-400 text-sm")
144
+
145
+ async def set_example(text: str):
146
+ search_input.value = text
147
+
148
+ for example in [
149
+ "cardiovascular effects of intermittent fasting",
150
+ "sleep deprivation and cognitive performance",
151
+ "gut microbiome and mental health",
152
+ ]:
153
+ ui.button(
154
+ example,
155
+ on_click=lambda e=example: set_example(e),
156
+ ).props("flat dense").classes("example-btn")
157
+
158
+ # Results container
159
+ results_container = ui.column().classes("w-full mt-6")
ui/styles.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Custom CSS styles for the Necthrall UI."""
2
+
3
+ CUSTOM_CSS = """
4
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
5
+
6
+ :root {
7
+ --primary: #f97316;
8
+ --primary-light: #fb923c;
9
+ --bg-light: #f8fafc;
10
+ --bg-white: #ffffff;
11
+ --bg-card: #ffffff;
12
+ --text-primary: #1e293b;
13
+ --text-secondary: #64748b;
14
+ --text-muted: #94a3b8;
15
+ --border-color: #e2e8f0;
16
+ --border-light: #f1f5f9;
17
+ --success: #10b981;
18
+ --link: #0ea5e9;
19
+ }
20
+
21
+ body {
22
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
23
+ background: var(--bg-light) !important;
24
+ }
25
+
26
+ .q-page {
27
+ background: var(--bg-light) !important;
28
+ }
29
+
30
+ /* Header */
31
+ .header-container {
32
+ background: var(--bg-white);
33
+ border-bottom: 1px solid var(--border-color);
34
+ padding: 12px 24px;
35
+ width: 100%;
36
+ }
37
+
38
+ .brand-logo {
39
+ height: 36px;
40
+ width: auto;
41
+ }
42
+
43
+ .brand-title {
44
+ font-weight: 700;
45
+ font-size: 1.5rem;
46
+ color: var(--text-primary);
47
+ letter-spacing: -0.02em;
48
+ }
49
+
50
+ /* Search */
51
+ .search-container {
52
+ max-width: 720px;
53
+ margin: 0 auto;
54
+ width: 100%;
55
+ }
56
+
57
+ .search-wrapper {
58
+ background: var(--bg-white);
59
+ border: 1px solid var(--border-color);
60
+ border-radius: 12px;
61
+ padding: 4px;
62
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
63
+ display: flex;
64
+ flex-wrap: nowrap;
65
+ align-items: center;
66
+ }
67
+
68
+ .search-input {
69
+ background: transparent !important;
70
+ border: none !important;
71
+ color: var(--text-primary) !important;
72
+ min-width: 0;
73
+ flex: 1;
74
+ }
75
+
76
+ .search-input .q-field__control {
77
+ background: transparent !important;
78
+ }
79
+
80
+ .search-input input {
81
+ color: var(--text-primary) !important;
82
+ font-size: 1rem;
83
+ }
84
+
85
+ .search-input input::placeholder {
86
+ color: var(--text-muted) !important;
87
+ }
88
+
89
+ .search-btn {
90
+ background: var(--primary) !important;
91
+ border-radius: 8px !important;
92
+ font-weight: 500 !important;
93
+ text-transform: none !important;
94
+ padding: 10px 20px !important;
95
+ color: white !important;
96
+ flex-shrink: 0;
97
+ white-space: nowrap;
98
+ }
99
+
100
+ .search-btn:hover {
101
+ background: var(--primary-light) !important;
102
+ }
103
+
104
+ /* Answer Section */
105
+ .answer-section {
106
+ background: var(--bg-white);
107
+ border: 1px solid var(--border-color);
108
+ border-radius: 12px;
109
+ padding: 24px;
110
+ margin-top: 24px;
111
+ }
112
+
113
+ .answer-text {
114
+ font-size: 1rem;
115
+ line-height: 1.8;
116
+ color: var(--text-primary);
117
+ }
118
+
119
+ /* Markdown styling within answer */
120
+ .answer-text ul, .answer-text ol {
121
+ margin: 0.5rem 0;
122
+ padding-left: 1.5rem;
123
+ }
124
+
125
+ .answer-text li {
126
+ margin-bottom: 0.5rem;
127
+ }
128
+
129
+ .answer-text p {
130
+ margin-bottom: 0.75rem;
131
+ }
132
+
133
+ .answer-text strong {
134
+ font-weight: 600;
135
+ }
136
+
137
+ .answer-text code {
138
+ background: var(--bg-light);
139
+ padding: 2px 6px;
140
+ border-radius: 4px;
141
+ font-size: 0.9em;
142
+ }
143
+
144
+ .answer-text sup {
145
+ color: var(--link);
146
+ font-weight: 600;
147
+ cursor: pointer;
148
+ }
149
+
150
+ /* Sources Section */
151
+ .sources-section {
152
+ margin-top: 24px;
153
+ }
154
+
155
+ .sources-title {
156
+ font-weight: 600;
157
+ font-size: 0.875rem;
158
+ color: var(--text-secondary);
159
+ text-transform: uppercase;
160
+ letter-spacing: 0.05em;
161
+ margin-bottom: 12px;
162
+ }
163
+
164
+ .source-card {
165
+ background: var(--bg-white);
166
+ border: 1px solid var(--border-color);
167
+ border-radius: 10px;
168
+ margin-bottom: 12px;
169
+ transition: border-color 0.2s, box-shadow 0.2s;
170
+ width: 100%;
171
+ }
172
+
173
+ .source-card .q-expansion-item__container {
174
+ border-radius: 10px;
175
+ }
176
+
177
+ .source-card .q-item {
178
+ padding: 16px;
179
+ }
180
+
181
+ .source-card:hover {
182
+ border-color: var(--primary);
183
+ box-shadow: 0 2px 8px rgba(249, 115, 22, 0.08);
184
+ }
185
+
186
+ .passage-content {
187
+ padding: 0 16px 16px 16px;
188
+ background: var(--bg-light);
189
+ border-top: 1px solid var(--border-light);
190
+ }
191
+
192
+ .source-title {
193
+ font-weight: 600;
194
+ font-size: 0.95rem;
195
+ color: var(--text-primary);
196
+ line-height: 1.4;
197
+ margin-bottom: 4px;
198
+ }
199
+
200
+ .source-meta {
201
+ font-size: 0.8rem;
202
+ color: var(--text-muted);
203
+ }
204
+
205
+ .source-link {
206
+ display: inline-flex;
207
+ align-items: center;
208
+ gap: 4px;
209
+ font-size: 0.8rem;
210
+ color: var(--text-muted);
211
+ background: var(--bg-light);
212
+ padding: 4px 10px;
213
+ border-radius: 6px;
214
+ font-weight: 500;
215
+ margin-top: 8px;
216
+ }
217
+
218
+ .source-link-btn {
219
+ display: inline-flex;
220
+ align-items: center;
221
+ gap: 4px;
222
+ font-size: 0.8rem;
223
+ color: var(--success) !important;
224
+ background: rgba(16, 185, 129, 0.1);
225
+ padding: 6px 12px;
226
+ border-radius: 6px;
227
+ font-weight: 500;
228
+ text-decoration: none !important;
229
+ transition: background 0.2s;
230
+ cursor: pointer;
231
+ }
232
+
233
+ .source-link-btn:hover {
234
+ background: rgba(16, 185, 129, 0.2);
235
+ text-decoration: none !important;
236
+ }
237
+
238
+ a.source-link-btn {
239
+ color: var(--success) !important;
240
+ text-decoration: none !important;
241
+ }
242
+
243
+ a.source-link-btn:visited {
244
+ color: var(--success) !important;
245
+ }
246
+
247
+ .source-link-btn .nicegui-label {
248
+ color: inherit !important;
249
+ }
250
+
251
+ .source-link-badge {
252
+ display: inline-flex;
253
+ align-items: center;
254
+ gap: 4px;
255
+ font-size: 0.75rem;
256
+ color: var(--text-muted);
257
+ background: var(--bg-light);
258
+ padding: 4px 10px;
259
+ border-radius: 6px;
260
+ font-weight: 500;
261
+ }
262
+
263
+ .source-snippet {
264
+ font-size: 0.875rem;
265
+ color: var(--text-secondary);
266
+ line-height: 1.6;
267
+ margin-top: 8px;
268
+ padding-top: 8px;
269
+ border-top: 1px solid var(--border-light);
270
+ }
271
+
272
+ /* Loading */
273
+ .loading-container {
274
+ text-align: center;
275
+ padding: 48px;
276
+ background: var(--bg-white);
277
+ border-radius: 12px;
278
+ border: 1px solid var(--border-color);
279
+ }
280
+
281
+ .loading-text {
282
+ color: var(--text-secondary);
283
+ font-size: 1rem;
284
+ margin-top: 16px;
285
+ font-weight: 500;
286
+ }
287
+
288
+ /* Stats Badge */
289
+ .stats-badge {
290
+ background: var(--bg-light);
291
+ color: var(--text-secondary);
292
+ padding: 4px 10px;
293
+ border-radius: 6px;
294
+ font-size: 0.75rem;
295
+ font-weight: 500;
296
+ }
297
+
298
+ /* Error */
299
+ .error-card {
300
+ background: #fef2f2 !important;
301
+ border: 1px solid #fecaca !important;
302
+ border-radius: 12px !important;
303
+ padding: 24px;
304
+ }
305
+
306
+ /* Menu icon */
307
+ .menu-icon {
308
+ color: var(--text-secondary);
309
+ cursor: pointer;
310
+ }
311
+
312
+ .menu-icon:hover {
313
+ color: var(--text-primary);
314
+ }
315
+
316
+ /* Mobile responsive */
317
+ @media (max-width: 640px) {
318
+ .search-container {
319
+ padding: 0 16px;
320
+ }
321
+
322
+ .brand-title {
323
+ font-size: 1.25rem;
324
+ }
325
+
326
+ .answer-section {
327
+ padding: 16px;
328
+ }
329
+
330
+ .source-card {
331
+ padding: 12px;
332
+ }
333
+
334
+ .header-container {
335
+ padding: 10px 16px;
336
+ }
337
+ }
338
+
339
+ @media (max-width: 480px) {
340
+ .search-btn {
341
+ padding: 8px 12px !important;
342
+ font-size: 0.875rem !important;
343
+ }
344
+
345
+ .example-queries {
346
+ flex-direction: column;
347
+ align-items: stretch;
348
+ }
349
+
350
+ .example-btn {
351
+ justify-content: center;
352
+ }
353
+ }
354
+
355
+ /* Example query buttons */
356
+ .example-queries {
357
+ display: flex;
358
+ flex-wrap: wrap;
359
+ gap: 8px;
360
+ justify-content: center;
361
+ padding: 0 16px;
362
+ }
363
+
364
+ .example-btn {
365
+ display: inline-flex;
366
+ align-items: center;
367
+ gap: 6px;
368
+ background: var(--bg-white) !important;
369
+ border: 1px solid var(--border-color) !important;
370
+ border-radius: 20px !important;
371
+ padding: 8px 16px !important;
372
+ font-size: 0.85rem !important;
373
+ color: var(--text-secondary) !important;
374
+ cursor: pointer;
375
+ transition: all 0.2s ease;
376
+ text-transform: none !important;
377
+ font-weight: 400 !important;
378
+ }
379
+
380
+ .example-btn:hover {
381
+ border-color: var(--primary) !important;
382
+ color: var(--primary) !important;
383
+ background: rgba(249, 115, 22, 0.05) !important;
384
+ }
385
+ """