File size: 12,707 Bytes
66700c2
 
 
 
a7fd580
66700c2
 
59cbda6
66700c2
 
 
 
 
 
 
eab0119
66700c2
a7fd580
66700c2
 
a7fd580
66700c2
 
 
 
 
 
 
 
 
 
 
 
 
59cbda6
 
b690278
59cbda6
acf2bbe
 
 
 
66700c2
 
 
a7fd580
 
66700c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59cbda6
 
 
 
 
 
acf2bbe
59cbda6
66700c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee163e3
 
acf2bbe
b5897db
 
acf2bbe
 
 
b690278
 
66700c2
 
 
 
 
 
ee163e3
b690278
 
d7e3980
b690278
2568a5f
b690278
b5897db
 
 
66700c2
 
a7fd580
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59cbda6
ee163e3
b690278
 
d7e3980
b690278
2568a5f
b690278
b5897db
 
 
59cbda6
a7fd580
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66700c2
a7fd580
 
66700c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59cbda6
acf2bbe
66700c2
 
 
 
 
 
 
 
59cbda6
acf2bbe
66700c2
 
 
 
 
 
 
59cbda6
 
 
 
 
 
 
 
66700c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59cbda6
acf2bbe
66700c2
 
 
 
 
 
 
 
 
 
59cbda6
acf2bbe
66700c2
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
"""Ad-hoc analysis endpoints (paste/upload text, PDF)."""

from __future__ import annotations

import logging
import io
import re
import json
from datetime import datetime
from typing import Any, Dict, List, Optional

from fastapi import APIRouter, File, Form, HTTPException, UploadFile
from pydantic import BaseModel, Field

from .conversation_service import run_resource_agent_analysis
from .storage_service import get_run_store, get_persona_store
from config.settings import get_settings
from backend.storage import RunRecord

router = APIRouter(prefix="", tags=["analysis"])
logger = logging.getLogger(__name__)


class ExportMessage(BaseModel):
    role: str
    persona: Optional[str] = None
    time: Optional[str] = None
    text: str


class AnalyzeTextRequest(BaseModel):
    text: str = Field(..., description="Raw transcript text to analyze")
    conversation_id: Optional[str] = Field(default=None, description="Optional client-generated id for this analysis run")
    source_name: Optional[str] = Field(default=None, description="Optional label for the uploaded/pasted source")
    analysis_attributes: Optional[List[str]] = Field(
        default=None,
        description="(Deprecated) analysis attributes are now configured per-pass server-side",
    )
    top_down_codebook_template_id: Optional[str] = Field(
        default=None,
        description="Top-down codebook template id to use for analysis (optional).",
    )


class AnalyzeTextResponse(BaseModel):
    run_id: Optional[str] = None
    persisted: bool = False
    conversation_id: str
    messages: List[ExportMessage]
    resources: Dict[str, Any]


def _parse_transcript_text(text: str, source_name: Optional[str]) -> List[Dict[str, Any]]:
    normalized = (text or "").replace("\r\n", "\n").replace("\r", "\n").strip()
    if not normalized:
        return []

    label = source_name or "Uploaded transcript"
    lines = [line.rstrip() for line in normalized.split("\n")]
    labeled = False
    blocks: List[Dict[str, Any]] = []

    current_role: Optional[str] = None
    current_lines: List[str] = []

    def flush():
        nonlocal current_role, current_lines
        content = "\n".join([l for l in current_lines]).strip()
        if content:
            role = current_role or "transcript"
            persona = "Surveyor" if role == "surveyor" else ("Patient" if role == "patient" else label)
            blocks.append({
                "role": role,
                "persona": persona,
                "content": content,
            })
        current_role = None
        current_lines = []

    pattern = re.compile(r"^(surveyor|interviewer|patient|respondent)\s*:\s*(.*)$", re.IGNORECASE)

    for line in lines:
        stripped = line.strip()
        if not stripped:
            if current_lines:
                current_lines.append("")
            continue

        match = pattern.match(stripped)
        if match:
            labeled = True
            flush()
            speaker = match.group(1).lower()
            current_role = "surveyor" if speaker in ("surveyor", "interviewer") else "patient"
            remainder = match.group(2).strip()
            if remainder:
                current_lines.append(remainder)
            continue

        if current_role is None:
            current_role = "transcript"
        current_lines.append(line)

    flush()

    if labeled:
        return blocks

    paragraphs = [p.strip() for p in re.split(r"\n\s*\n+", normalized) if p.strip()]
    return [{
        "role": "transcript",
        "persona": label,
        "content": p,
    } for p in paragraphs] or [{
        "role": "transcript",
        "persona": label,
        "content": normalized,
    }]


async def _analyze_from_text(
    *,
    text: str,
    conversation_id: str,
    source_name: Optional[str],
    analysis_attributes: Optional[List[str]] = None,
    top_down_codebook_template_id: Optional[str] = None,
) -> AnalyzeTextResponse:
    settings = get_settings()
    exported_at = datetime.now().isoformat()

    parsed_messages = _parse_transcript_text(text, source_name)
    if not parsed_messages:
        raise HTTPException(status_code=400, detail="No content to analyze")

    transcript: List[Dict[str, Any]] = []
    ui_messages: List[ExportMessage] = []
    for idx, msg in enumerate(parsed_messages):
        transcript.append({
            "index": idx,
            "role": msg["role"],
            "persona": msg.get("persona"),
            "content": msg["content"],
            "timestamp": exported_at,
        })
        ui_messages.append(ExportMessage(
            role=msg["role"],
            persona=msg.get("persona"),
            time=exported_at,
            text=msg["content"],
        ))

    store = get_persona_store()
    effective_analysis_system_prompt = await store.get_setting("analysis_system_prompt")
    override = top_down_codebook_template_id.strip() if isinstance(top_down_codebook_template_id, str) else ""
    template_id = await store.get_setting("top_down_codebook_template_id")
    template_id_str = template_id.strip() if isinstance(template_id, str) else ""
    template_record = await store.get_analysis_template(override, include_deleted=False) if override else None
    if not template_record and template_id_str:
        template_record = await store.get_analysis_template(template_id_str, include_deleted=False)
    if not template_record and template_id_str:
        raise HTTPException(status_code=500, detail="Default analysis framework template not found")
    resources = await run_resource_agent_analysis(
        transcript=transcript,
        llm_backend=settings.llm.backend,
        host=settings.llm.host,
        model=settings.llm.model,
        settings=settings,
        analysis_system_prompt=effective_analysis_system_prompt if isinstance(effective_analysis_system_prompt, str) else None,
        bottom_up_instructions=template_record.bottom_up_instructions if template_record else None,
        bottom_up_attributes=template_record.bottom_up_attributes if template_record else None,
        rubric_instructions=template_record.rubric_instructions if template_record else None,
        rubric_attributes=template_record.rubric_attributes if template_record else None,
        top_down_instructions=template_record.top_down_instructions if template_record else None,
        top_down_attributes=template_record.top_down_attributes if template_record else None,
        top_down_template_id=template_record.template_id if template_record else template_id_str,
        top_down_template_version_id=template_record.current_version_id if template_record else "",
        top_down_template_categories=template_record.categories if template_record else [],
    )

    persisted = False
    run_id = None
    try:
        store = get_run_store()
        run_id = conversation_id
        config_snapshot: Dict[str, Any] = {
            "llm": {
                "backend": settings.llm.backend,
                "host": settings.llm.host,
                "model": settings.llm.model,
                "timeout": settings.llm.timeout,
                "max_retries": settings.llm.max_retries,
                "retry_delay": settings.llm.retry_delay,
            },
            "text_analysis": {
                "source_name": source_name,
            },
            "analysis": {
                "analysis_system_prompt": effective_analysis_system_prompt if isinstance(effective_analysis_system_prompt, str) else None,
                "bottom_up_instructions": template_record.bottom_up_instructions if template_record else None,
                "bottom_up_attributes": template_record.bottom_up_attributes if template_record else None,
                "rubric_instructions": template_record.rubric_instructions if template_record else None,
                "rubric_attributes": template_record.rubric_attributes if template_record else None,
                "top_down_instructions": template_record.top_down_instructions if template_record else None,
                "top_down_attributes": template_record.top_down_attributes if template_record else None,
                "top_down_codebook_template_id": template_record.template_id if template_record else template_id_str,
                "top_down_codebook_template_version_id": template_record.current_version_id if template_record else "",
                "top_down_codebook_template_snapshot": template_record.categories if template_record else [],
            },
        }
        record = RunRecord(
            run_id=run_id,
            mode="text_analysis",
            status="completed",
            created_at=exported_at,
            ended_at=exported_at,
            sealed_at=exported_at,
            title=None,
            input_summary=source_name,
            config=config_snapshot,
            messages=transcript,
            analyses={"resource_agent_v2": resources},
            persona_snapshots={},
        )
        await store.save_sealed_run(record)
        persisted = True
    except Exception as e:
        logger.error(f"Failed to persist sealed text analysis {conversation_id}: {e}")
        persisted = False
        run_id = None

    return AnalyzeTextResponse(
        run_id=run_id,
        persisted=persisted,
        conversation_id=conversation_id,
        messages=ui_messages,
        resources=resources,
    )


@router.post("/analyze/text")
async def analyze_text(payload: AnalyzeTextRequest) -> AnalyzeTextResponse:
    if not isinstance(payload.text, str) or not payload.text.strip():
        raise HTTPException(status_code=400, detail="text is required")

    conversation_id = payload.conversation_id or f"analysis_{int(datetime.now().timestamp())}"
    return await _analyze_from_text(
        text=payload.text,
        conversation_id=conversation_id,
        source_name=payload.source_name,
        analysis_attributes=payload.analysis_attributes,
        top_down_codebook_template_id=payload.top_down_codebook_template_id,
    )


@router.post("/analyze/file")
async def analyze_file(
    file: UploadFile = File(...),
    conversation_id: Optional[str] = Form(default=None),
    source_name: Optional[str] = Form(default=None),
    analysis_attributes_json: Optional[str] = Form(default=None),
    top_down_codebook_template_id: Optional[str] = Form(default=None),
) -> AnalyzeTextResponse:
    data = await file.read()
    if not data:
        raise HTTPException(status_code=400, detail="Empty file")

    inferred_name = source_name or file.filename or "Uploaded file"
    cid = conversation_id or f"analysis_{int(datetime.now().timestamp())}"
    analysis_attributes: Optional[List[str]] = None
    if isinstance(analysis_attributes_json, str) and analysis_attributes_json.strip():
        try:
            parsed = json.loads(analysis_attributes_json)
            if isinstance(parsed, list):
                analysis_attributes = [str(x).strip() for x in parsed if isinstance(x, str) and str(x).strip()]
        except Exception:
            analysis_attributes = None

    filename = (file.filename or "").lower()
    content_type = (file.content_type or "").lower()

    is_pdf = filename.endswith(".pdf") or content_type == "application/pdf"
    if is_pdf:
        try:
            from pypdf import PdfReader  # type: ignore
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"pypdf not available: {e}")

        try:
            reader = PdfReader(io.BytesIO(data))
            chunks: List[str] = []
            for page in reader.pages:
                page_text = (page.extract_text() or "").strip()
                if page_text:
                    chunks.append(page_text)
            extracted = "\n\n".join(chunks).strip()
        except Exception as e:
            raise HTTPException(status_code=400, detail=f"Failed to parse PDF: {e}")

        if not extracted:
            raise HTTPException(status_code=400, detail="No extractable text found in PDF")

        return await _analyze_from_text(
            text=extracted,
            conversation_id=cid,
            source_name=inferred_name,
            analysis_attributes=analysis_attributes,
            top_down_codebook_template_id=top_down_codebook_template_id,
        )

    decoded = data.decode("utf-8", errors="replace").strip()
    if not decoded:
        raise HTTPException(status_code=400, detail="No text content found in file")

    return await _analyze_from_text(
        text=decoded,
        conversation_id=cid,
        source_name=inferred_name,
        analysis_attributes=analysis_attributes,
        top_down_codebook_template_id=top_down_codebook_template_id,
    )