File size: 12,445 Bytes
3f43e82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
338
339
340
341
342
343
344
import streamlit as st
import httpx
import os
import io
from dotenv import load_dotenv
import logging
import asyncio
from streamlit_mic_recorder import mic_recorder


logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
load_dotenv()

ORCHESTRATOR_URL = os.getenv("ORCHESTRATOR_URL")


if "processing_state" not in st.session_state:
    st.session_state.processing_state = "initial"
if "orchestrator_response" not in st.session_state:
    st.session_state.orchestrator_response = None
if "audio_bytes_input" not in st.session_state:
    st.session_state.audio_bytes_input = None
if "audio_filename" not in st.session_state:
    st.session_state.audio_filename = None
if "audio_filetype" not in st.session_state:
    st.session_state.audio_filetype = None
if "last_audio_source" not in st.session_state:
    st.session_state.last_audio_source = None
if "current_recording_id" not in st.session_state:
    st.session_state.current_recording_id = None


async def call_orchestrator(audio_bytes: bytes, filename: str, content_type: str):

    url = f"{ORCHESTRATOR_URL}/market_brief"
    files = {"audio": (filename, audio_bytes, content_type)}
    logger.info(
        f"Calling orchestrator at {url} with audio file: {filename} ({content_type})"
    )
    try:
        async with httpx.AsyncClient() as client:
            response = await client.post(url, files=files, timeout=180.0)
            response.raise_for_status()
            logger.info(f"Orchestrator returned status {response.status_code}.")
            return response.json()
    except httpx.RequestError as e:
        error_msg = f"HTTP Request failed: {e}"
        logger.error(error_msg)
        return {
            "status": "error",
            "message": "Error communicating with orchestrator.",
            "errors": [error_msg],
            "transcript": None,
            "brief": None,
            "audio": None,
        }
    except Exception as e:
        error_msg = f"An unexpected error occurred: {e}"
        logger.error(error_msg)
        return {
            "status": "error",
            "message": "An unexpected error occurred.",
            "errors": [error_msg],
            "transcript": None,
            "brief": None,
            "audio": None,
        }


st.set_page_config(layout="wide")
st.title("📈 AI Financial Assistant - Morning Market Brief")
st.markdown(
    "Ask your query verbally (e.g., 'What's our risk exposure in Asia tech stocks today, and highlight any earnings surprises?') "
    "or upload an audio file."
)

input_method = st.radio(
    "Choose input method:",
    ("Record Audio", "Upload File"),
    horizontal=True,
    index=0,
    key="input_method_radio",
)

audio_data_ready = False


if st.session_state.audio_bytes_input is not None:
    audio_data_ready = True


if input_method == "Record Audio":
    st.subheader("Record Your Query")

    if st.session_state.last_audio_source == "uploader":
        st.session_state.audio_bytes_input = None
        st.session_state.audio_filename = None
        st.session_state.audio_filetype = None
        st.session_state.last_audio_source = "recorder"
        audio_data_ready = False

    audio_info = mic_recorder(
        start_prompt="⏺️ Start Recording",
        stop_prompt="⏹️ Stop Recording",
        just_once=False,
        use_container_width=True,
        format="wav",
        key="mic_recorder_widget",
    )

    if audio_info and audio_info.get("bytes"):

        if st.session_state.current_recording_id != audio_info.get("id"):
            st.session_state.current_recording_id = audio_info.get("id")
            st.success("Recording complete! Click 'Generate Market Brief' below.")
            st.session_state.audio_bytes_input = audio_info["bytes"]
            st.session_state.audio_filename = f"live_recording_{audio_info['id']}.wav"
            st.session_state.audio_filetype = "audio/wav"
            st.session_state.last_audio_source = "recorder"
            audio_data_ready = True
            st.session_state.processing_state = "initial"
            st.session_state.orchestrator_response = None
            st.audio(audio_info["bytes"])

        elif st.session_state.audio_bytes_input:
            audio_data_ready = True
            st.audio(st.session_state.audio_bytes_input)

    elif (
        st.session_state.last_audio_source == "recorder"
        and st.session_state.audio_bytes_input
    ):
        st.markdown("Using last recording:")
        st.audio(st.session_state.audio_bytes_input)
        audio_data_ready = True


elif input_method == "Upload File":
    st.subheader("Upload Audio File")

    if st.session_state.last_audio_source == "recorder":
        st.session_state.audio_bytes_input = None
        st.session_state.audio_filename = None
        st.session_state.audio_filetype = None
        st.session_state.last_audio_source = "uploader"
        st.session_state.current_recording_id = None
        audio_data_ready = False

    if "uploaded_file_state" not in st.session_state:
        st.session_state.uploaded_file_state = None

    uploaded_file = st.file_uploader(
        "Select Audio File",
        type=["wav", "mp3", "m4a", "ogg", "flac"],
        key="file_uploader_key",
    )

    if uploaded_file is not None:
        if st.session_state.uploaded_file_state != uploaded_file:
            st.session_state.uploaded_file_state = uploaded_file
            st.session_state.audio_bytes_input = uploaded_file.getvalue()
            st.session_state.audio_filename = uploaded_file.name
            st.session_state.audio_filetype = uploaded_file.type
            st.session_state.last_audio_source = "uploader"
            audio_data_ready = True
            st.session_state.processing_state = "initial"
            st.session_state.orchestrator_response = None
            st.success(f"File '{uploaded_file.name}' ready.")
            st.audio(
                st.session_state.audio_bytes_input,
                format=st.session_state.audio_filetype,
            )
        elif st.session_state.audio_bytes_input:
            audio_data_ready = True
            st.audio(
                st.session_state.audio_bytes_input,
                format=st.session_state.audio_filetype,
            )

    elif (
        st.session_state.last_audio_source == "uploader"
        and st.session_state.audio_bytes_input
    ):
        st.markdown("Using last uploaded file:")
        st.audio(
            st.session_state.audio_bytes_input, format=st.session_state.audio_filetype
        )
        audio_data_ready = True


st.divider()
button_disabled = (
    not audio_data_ready or st.session_state.processing_state == "processing"
)

if st.button(
    "Generate Market Brief",
    disabled=button_disabled,
    type="primary",
    use_container_width=True,
    key="generate_button",
):
    if st.session_state.audio_bytes_input:
        st.session_state.processing_state = "processing"
        st.session_state.orchestrator_response = None
        logger.info(
            f"Generate Market Brief button clicked. Source: {st.session_state.last_audio_source}, Filename: {st.session_state.audio_filename}"
        )
        st.rerun()
    else:
        st.warning("Please record or upload an audio query first.")


if st.session_state.processing_state == "processing":
    if (
        st.session_state.audio_bytes_input
        and st.session_state.audio_filename
        and st.session_state.audio_filetype
    ):
        with st.spinner("Processing your request... This may take a moment. 🤖"):

            logger.info(
                f"Calling orchestrator with filename: {st.session_state.audio_filename}, type: {st.session_state.audio_filetype}, bytes: {len(st.session_state.audio_bytes_input)}"
            )
            try:
                response = asyncio.run(
                    call_orchestrator(
                        st.session_state.audio_bytes_input,
                        st.session_state.audio_filename,
                        st.session_state.audio_filetype,
                    )
                )
                st.session_state.orchestrator_response = response

                is_successful_response = True
                if not response:
                    is_successful_response = False
                elif (
                    response.get("status") == "error"
                    or response.get("status") == "failed"
                ):
                    is_successful_response = False
                elif response.get("errors") and len(response.get("errors")) > 0:
                    is_successful_response = False

                st.session_state.processing_state = (
                    "completed" if is_successful_response else "error"
                )

            except Exception as e:
                logger.error(
                    f"Error during orchestrator call in Streamlit: {e}", exc_info=True
                )
                st.session_state.orchestrator_response = {
                    "status": "error",
                    "message": f"Streamlit failed to call orchestrator: {str(e)}",
                    "errors": [str(e)],
                    "transcript": None,
                    "brief": None,
                    "audio": None,
                }
                st.session_state.processing_state = "error"
        st.rerun()
    else:
        st.error("Audio data is missing for processing. Please record or upload again.")
        st.session_state.processing_state = "initial"


if st.session_state.processing_state in ["completed", "error"]:

    response = st.session_state.orchestrator_response
    st.subheader("📝 Results")

    if response is None:
        st.error("No response received from the orchestrator.")

    elif (
        response.get("status") == "failed"
        or response.get("status") == "error"
        or (response.get("errors") and len(response.get("errors")) > 0)
    ):
        st.error(
            f"Workflow {response.get('status', 'failed')}: {response.get('message', 'Check errors below.')}"
        )
        if response.get("errors"):
            st.warning("Details of Errors:")
            for i, err in enumerate(response["errors"]):
                st.markdown(f"`Error {i+1}`: {err}")
        if response.get("warnings"):
            st.warning("Details of Warnings:")
            for i, warn in enumerate(response["warnings"]):
                st.markdown(f"`Warning {i+1}`: {warn}")

        if response.get("transcript"):
            st.markdown("---")
            st.markdown("Transcript (despite errors):")
            st.caption(response.get("transcript"))
        if response.get("brief"):
            st.markdown("---")
            st.markdown("Generated Brief (despite errors):")
            st.caption(response.get("brief"))
    else:
        st.success(response.get("message", "Market brief generated successfully!"))
        if response.get("transcript"):
            st.markdown("---")
            st.markdown("Your Query (Transcript):")
            st.caption(response.get("transcript"))
        else:
            st.info("Transcript not available.")

        if response.get("brief"):
            st.markdown("---")
            st.markdown("Generated Brief:")
            st.write(response.get("brief"))
        else:
            st.info("Brief text not available.")

        audio_hex = response.get("audio")
        if audio_hex:
            st.markdown("---")
            st.markdown("Audio Brief:")
            try:
                if not isinstance(audio_hex, str) or not all(
                    c in "0123456789abcdefABCDEF" for c in audio_hex
                ):
                    raise ValueError("Invalid hex string for audio.")
                audio_bytes_output = bytes.fromhex(audio_hex)
                st.audio(audio_bytes_output, format="audio/mpeg")
            except ValueError as ve:
                st.error(f"⚠️ Failed to decode audio data: {ve}")
            except Exception as e:
                st.error(f"⚠️ Failed to play audio: {e}")
        else:
            st.info("Audio brief not available.")

        if response.get("warnings"):
            st.markdown("---")
            st.warning("Process Warnings:")
            for i, warn in enumerate(response["warnings"]):
                st.markdown(f"`Warning {i+1}`: {warn}")