File size: 10,496 Bytes
4488b44
72afe31
 
4488b44
 
55ff7de
4488b44
 
 
 
55ff7de
4488b44
 
aa662d8
83efdfc
 
 
aa662d8
72afe31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa662d8
 
889ca74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa662d8
 
 
 
 
889ca74
 
aa662d8
 
 
889ca74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0072475
889ca74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa662d8
83efdfc
55ff7de
 
4488b44
aa662d8
4488b44
 
2a0c436
 
 
 
 
 
 
 
 
 
55ff7de
 
 
2a0c436
 
 
 
 
 
 
 
 
 
 
55ff7de
 
2a0c436
 
4488b44
 
83efdfc
4488b44
72afe31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4488b44
83efdfc
55ff7de
 
4488b44
 
aa662d8
 
2a0c436
 
 
4488b44
72afe31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55ff7de
72afe31
 
 
 
4488b44
72afe31
 
 
 
4488b44
 
 
 
 
 
 
 
 
 
 
 
 
72afe31
 
4488b44
 
 
55ff7de
aa662d8
4488b44
 
 
 
72afe31
4488b44
 
 
72afe31
4488b44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import json
import sys
import threading
from queue import Empty, Queue
from threading import Thread
from typing import List, Optional

from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, Field

from pipeline import pipeline as run_pipeline
from persona.make_persona import make_persona

app = FastAPI()


class _ThreadStdoutProxy:
    def __init__(self, target):
        self._target = target
        self._handlers = {}
        self._lock = threading.RLock()
        self.encoding = getattr(target, "encoding", "utf-8")
        self.errors = getattr(target, "errors", None)

    def register(self, thread_id: int, handler) -> None:
        with self._lock:
            self._handlers[thread_id] = handler

    def unregister(self, thread_id: int) -> None:
        with self._lock:
            self._handlers.pop(thread_id, None)

    def _resolve(self):
        thread_id = threading.get_ident()
        with self._lock:
            return self._handlers.get(thread_id), self._target

    def write(self, data):
        handler, target = self._resolve()
        if handler:
            return handler.write(data)
        return target.write(data)

    def flush(self):
        handler, target = self._resolve()
        if handler:
            handler.flush()
        return target.flush()

    def isatty(self):
        return getattr(self._target, "isatty", lambda: False)()

    def fileno(self):
        return self._target.fileno()

    def writable(self):
        return True

    def __getattr__(self, name):
        return getattr(self._target, name)


class _QueueingStdoutTee:
    def __init__(self, target, event_queue: Queue):
        self._target = target
        self._event_queue = event_queue

    def write(self, data):
        written = self._target.write(data)
        if data:
            self._event_queue.put({"type": "stdout", "message": data})
        return written

    def flush(self):
        self._target.flush()


_stdout_proxy = _ThreadStdoutProxy(sys.stdout)
sys.stdout = _stdout_proxy


class PersonaRequest(BaseModel):
    info: str
    stream: bool = True


PERSONA_STATUS_MESSAGES = [
    "인물 정보 μˆ˜μ§‘ 쀑...",
    "μ›Ή 검색을 톡해 λ°°κ²½ 쑰사 쀑...",
    "금육 사고 방식 뢄석 쀑...",
    "데이터 뢄석 접근법 평가 쀑...",
    "λ‹΅λ³€ μŠ€νƒ€μΌ νŠΉμ„± νŒŒμ•… 쀑...",
    "핡심 투자 원칙 μΆ”μΆœ 쀑...",
    "λŒ€ν‘œ 어둝 정리 쀑...",
    "페λ₯΄μ†Œλ‚˜ ν”„λ‘œν•„ ꡬ성 쀑...",
    "μ΅œμ’… 검증 및 μ €μž₯ μ€€λΉ„ 쀑...",
]


def _build_persona_payload(persona) -> dict:
    return {
        "type": "result",
        "name": persona.name,
        "full_name": persona.full_name,
        "summary": persona.summary,
        "financial_mindset": persona.financial_mindset,
        "data_analysis_approach": persona.data_analysis_approach,
        "response_style": persona.response_style,
        "key_principles": persona.key_principles,
        "famous_quotes": getattr(persona, "famous_quotes", None),
    }


@app.post("/persona/")
async def create_persona(request: PersonaRequest):
    info = (request.info or "").strip()
    stream = request.stream

    if not info:
        return JSONResponse(status_code=400, content={"error": "info ν•„λ“œκ°€ λΉ„μ–΄ μžˆμŠ΅λ‹ˆλ‹€."})

    if not stream:
        try:
            persona = make_persona(info)
        except Exception as exc:
            return JSONResponse(status_code=500, content={"error": str(exc)})

        if persona is None:
            return JSONResponse(status_code=500, content={"error": "페λ₯΄μ†Œλ‚˜ 생성에 μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€."})

        return JSONResponse(content=persona.model_dump())

    def event_stream():
        event_queue: Queue = Queue()

        def status_sender():
            import asyncio

            async def send_status():
                for i, message in enumerate(PERSONA_STATUS_MESSAGES[:-1]):  # λ§ˆμ§€λ§‰ λ©”μ‹œμ§€λŠ” μ™„λ£Œ μ‹œμ μ— μ‚¬μš©
                    event_queue.put({"type": "status", "message": message})
                    await asyncio.sleep(8)

            # 비동기 이벀트 λ£¨ν”„μ—μ„œ μ‹€ν–‰
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            loop.run_until_complete(send_status())

        def worker():
            thread_id = threading.get_ident()
            _stdout_proxy.register(thread_id, _QueueingStdoutTee(_stdout_proxy._target, event_queue))
            try:
                # status λ©”μ‹œμ§€ 전솑 μŠ€λ ˆλ“œ μ‹œμž‘
                status_thread = Thread(target=status_sender, daemon=True)
                status_thread.start()

                persona = make_persona(info)

                if persona is None:
                    event_queue.put({"type": "error", "message": "페λ₯΄μ†Œλ‚˜ 생성에 μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€."})
                else:
                    event_queue.put(_build_persona_payload(persona))
            except Exception as exc:
                event_queue.put({"type": "error", "message": str(exc)})
            finally:
                _stdout_proxy.unregister(thread_id)
                event_queue.put({"type": "done"})

        yield _sse({"type": "status", "message": "페λ₯΄μ†Œλ‚˜ 생성 μ€€λΉ„ 쀑..."})
        Thread(target=worker, daemon=True).start()

        done = False
        while not done:
            try:
                event = event_queue.get(timeout=0.2)
            except Empty:
                continue
            yield _sse(jsonable_encoder(event))
            if event.get("type") == "done":
                done = True

    headers = {
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "X-Accel-Buffering": "no",
    }
    return StreamingResponse(event_stream(), media_type="text/event-stream", headers=headers)

class QueryRequest(BaseModel):
    query: str
    history: List["ChatMessage"] = Field(default_factory=list)
    stream: bool = True
    persona_name: Optional[str] = None


class ChatMessage(BaseModel):
    role: str
    content: str


def _normalize_chat_role(role: str) -> str:
    role = (role or "").strip().lower()
    return role


def _normalize_history_input(history_input):
    history = []
    for message in history_input or []:
        if isinstance(message, ChatMessage):
            role = _normalize_chat_role(message.role)
            content = (message.content or "").strip()
        elif isinstance(message, dict):
            role = _normalize_chat_role(message.get("role", ""))
            content = (message.get("content", "") or "").strip()
        else:
            continue

        if not role or not content:
            continue
        history.append({"role": role, "content": content})
    return history


def _sse(payload: dict) -> str:
    return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"


def _build_result_payload(result, stdout: str = "") -> dict:
    payload = {
        "type": "result",
        "query": result.query,
        "ticker": result.ticker,
        "analysis_type": result.analysis_type,
        "data_context": result.data_context,
        "llm_response": result.llm_response,
        "timestamp": getattr(result, "timestamp", None),
    }
    if stdout:
        payload["stdout"] = stdout
    return payload


@app.post("/analyze/")
async def analyze(request: QueryRequest):
    query = (request.query or "").strip()
    history = _normalize_history_input(request.history)
    stream = request.stream

    persona_name = (request.persona_name or "").strip() or None

    if not query:
        return JSONResponse(status_code=400, content={"error": "query ν•„λ“œκ°€ λΉ„μ–΄ μžˆμŠ΅λ‹ˆλ‹€."})

    if not stream:
        stdout_messages = []

        class _ListStdoutTee:
            def __init__(self, target):
                self._target = target

            def write(self, data):
                written = self._target.write(data)
                if data:
                    stdout_messages.append(data)
                return written

            def flush(self):
                self._target.flush()

        thread_id = threading.get_ident()
        _stdout_proxy.register(thread_id, _ListStdoutTee(_stdout_proxy._target))
        try:
            result = run_pipeline(
                query,
                history=history,
                persona_name=persona_name,
                status_callback=None,
                stream_callback=None,
                stream=False,
            )
        finally:
            _stdout_proxy.unregister(thread_id)
        return JSONResponse(
            content=jsonable_encoder(_build_result_payload(result, stdout="".join(stdout_messages)))
        )

    def event_stream():
        event_queue: Queue = Queue()

        def on_status(message: str):
            event_queue.put({"type": "status", "message": message})

        def on_delta(delta: str):
            if stream:
                event_queue.put({"type": "delta", "delta": delta})

        def worker():
            thread_id = threading.get_ident()
            _stdout_proxy.register(thread_id, _QueueingStdoutTee(_stdout_proxy._target, event_queue))
            try:
                result = run_pipeline(
                    query,
                    history=history,
                    persona_name=persona_name,
                    status_callback=on_status,
                    stream_callback=on_delta if stream else None,
                    stream=stream,
                )
                event_queue.put(_build_result_payload(result))
            except Exception as exc:
                event_queue.put({"type": "error", "message": str(exc)})
            finally:
                _stdout_proxy.unregister(thread_id)
                event_queue.put({"type": "done"})

        yield _sse({"type": "status", "message": "μš”μ²­ μˆ˜μ‹ . 뢄석 μ€€λΉ„ 쀑..."})
        Thread(target=worker, daemon=True).start()

        done = False
        while not done:
            try:
                event = event_queue.get(timeout=0.2)
            except Empty:
                continue
            yield _sse(jsonable_encoder(event))
            if event.get("type") == "done":
                done = True

    headers = {
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "X-Accel-Buffering": "no",
    }
    return StreamingResponse(event_stream(), media_type="text/event-stream", headers=headers)