File size: 8,335 Bytes
28ba0c9
 
7f75acb
28ba0c9
5b48ad6
 
 
28ba0c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f75acb
 
 
 
 
5b48ad6
32f8638
 
 
 
7f75acb
 
 
 
 
 
 
28ba0c9
7f75acb
 
 
 
28ba0c9
 
 
 
 
 
 
 
7f75acb
 
 
 
28ba0c9
9d7922d
 
 
28ba0c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b48ad6
 
32f8638
 
 
5b48ad6
28ba0c9
 
32f8638
28ba0c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1bbee2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32f8638
a1bbee2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
"""Reusable UI components for Necthrall."""

import json

from loguru import logger
from nicegui import ui


def render_loading():
    """Render the loading spinner with status text."""
    with ui.column().classes("loading-container w-full") as container:
        ui.spinner("dots", size="xl", color="#f97316")
        ui.label("Analyzing Research...").classes("loading-text")
        ui.label("Searching papers, extracting insights, synthesizing answer").classes(
            "text-slate-400 text-sm mt-2"
        )
    return container


def render_answer(result):
    """Render the answer section.

    Args:
        result: PipelineResult object with answer, execution_time, finalists, passages
    """

    def copy_content():
        """Construct and copy content to clipboard."""
        content = result.answer + "\n\n### Sources Cited\n"
        for idx, passage in enumerate(result.passages):
            metadata = getattr(passage, "metadata", {})
            title = metadata.get("paper_title") or metadata.get(
                "title", "Unknown Source"
            )
            url = metadata.get("pdf_url") or metadata.get("url", "")
            content += f"{idx + 1}. {title} - {url}\n"

        # Serialize to JSON to handle quotes/newlines safely
        safe_content = json.dumps(content)
        ui.run_javascript(f"navigator.clipboard.writeText({safe_content})")
        ui.notify("Copied to clipboard", type="positive")

    with ui.column().classes("answer-section w-full"):
        # Stats row - responsive layout
        with ui.row().classes("w-full justify-between items-start mb-4 no-wrap"):
            # Stats badges container - allows wrapping internally
            with ui.row().classes("flex-wrap gap-2 items-center"):
                ui.label(f"⏱️ {result.execution_time:.1f}s").classes("stats-badge")
                ui.label(f"πŸ“„ {len(result.finalists)} papers analyzed").classes(
                    "stats-badge"
                )
                ui.label(f"πŸ“ {len(result.passages)} sources cited").classes(
                    "stats-badge"
                )

            ui.button(icon="content_copy", on_click=copy_content).props(
                "flat round size=sm"
            ).classes("text-gray-500 shrink-0").tooltip("Copy to clipboard")

        # Answer text - clean up markdown and display
        ui.markdown(result.answer, extras=["tables"]).classes("w-full").style(
            "word-wrap: break-word; overflow-wrap: break-word; hyphens: auto; word-break: break-word; line-height: 1.8;"
        )


def render_sources(passages):
    """Render the sources section as cards.

    Args:
        passages: List of passage objects with node and score attributes
    """
    if not passages:
        return

    with ui.column().classes("sources-section w-full"):
        ui.label("SOURCES CITED").classes("sources-title")

        for idx, passage in enumerate(passages):
            try:
                # Extract passage info
                text = getattr(passage, "text", "")
                metadata = getattr(passage, "metadata", {})
                paper_title = metadata.get("paper_title") or metadata.get(
                    "title", "Unknown Source"
                )
                paper_id = getattr(passage, "paper_id", "")
                section = metadata.get("section", "")
                # Try to get PDF URL from metadata
                pdf_url = metadata.get("pdf_url") or metadata.get("url", "")

                with ui.expansion().classes("source-card").props("dense") as expansion:
                    # Header slot for title
                    with expansion.add_slot("header"):
                        with ui.column().classes("w-full"):
                            # Title
                            ui.label(paper_title).classes("source-title")

                            # Meta info
                            meta_parts = []
                            if section:
                                meta_parts.append(section)
                            meta_parts.append(f"Citation [{idx + 1}]")
                            ui.label(" β€’ ".join(meta_parts)).classes("source-meta")

                            # PDF link if available
                            if pdf_url:
                                with ui.row().classes("items-center mt-2"):
                                    with (
                                        ui.element("a")
                                        .props(f'href="{pdf_url}" target="_blank"')
                                        .classes("source-link-btn")
                                    ):
                                        ui.label("πŸ“„ Open Access PDF")
                            else:
                                with ui.row().classes("items-center mt-2"):
                                    ui.html(
                                        '<span class="source-link-badge">πŸ“„ PDF not available</span>',
                                        sanitize=False,
                                    )

                    # Expanded content - full passage
                    with ui.column().classes("passage-content"):
                        ui.label(text).classes("source-snippet")

            except Exception as e:
                logger.warning(f"Failed to render passage {idx}: {e}")
                continue


def render_error(error_message: str, error_stage: str = None):
    """Render an error card.

    Args:
        error_message: The error message to display
        error_stage: Optional stage where the error occurred
    """
    with ui.column().classes("error-card w-full"):
        with ui.row().classes("items-center gap-3"):
            ui.icon("error_outline", color="#ef4444", size="sm")
            ui.label("Analysis Failed").classes("text-lg font-semibold text-red-600")
        ui.label(error_message).classes("text-red-500 mt-2")
        if error_stage:
            ui.label(f"Stage: {error_stage}").classes("text-red-400 text-sm mt-1")


def render_exception_error(exception: Exception):
    """Render an error card for an exception.

    Args:
        exception: The exception that was raised
    """
    with ui.column().classes("error-card w-full"):
        ui.icon("error_outline", color="#ef4444", size="sm")
        ui.label("Error").classes("text-lg font-semibold text-red-600")
        ui.label(str(exception)).classes("text-red-500 mt-2")


class SearchProgress:
    """Vertical stepper to visualize search progress."""

    def __init__(self):
        with ui.column().classes("w-full items-center"):
            with ui.card().classes(
                "w-full max-w-md p-6 shadow-lg border border-slate-100"
            ):
                ui.label("Researching...").classes(
                    "text-xl font-bold text-slate-700 mb-4 text-center w-full"
                )
                self.stepper = (
                    ui.stepper().props("vertical animated flat").classes("w-full")
                )
                with self.stepper:
                    with ui.step("Refining Query"):
                        ui.label("Clarifying your research question...").classes(
                            "text-slate-600"
                        )

                    with ui.step("Searching Sources"):
                        ui.label("Scanning millions of open-access papers...").classes(
                            "text-slate-600"
                        )

                    with ui.step("Reading Documents"):
                        with ui.column().classes("gap-2"):
                            ui.label(
                                "Reading and processing retrieved content..."
                            ).classes("text-slate-600")
                            ui.spinner("dots", size="lg", color="primary")

                    with ui.step("Analyzing Data"):
                        ui.label("Extracting key evidence and citations...").classes(
                            "text-slate-600"
                        )

                    with ui.step("Writing Answer"):
                        ui.label("Drafting your cited summary...").classes(
                            "text-slate-600"
                        )

    def next_step(self):
        """Advance to the next step."""
        self.stepper.next()