File size: 12,267 Bytes
56bc4cf
 
33a4549
48a2803
c319a1e
56bc4cf
 
31df7d3
 
c319a1e
56bc4cf
3b0bca5
56bc4cf
33a4549
56bc4cf
 
 
 
31df7d3
56bc4cf
 
 
 
31df7d3
56bc4cf
 
 
 
 
 
 
 
 
33a4549
 
 
56bc4cf
31df7d3
48a2803
56bc4cf
33a4549
 
 
 
48a2803
31df7d3
 
 
 
33a4549
 
31df7d3
33a4549
 
 
 
 
48a2803
33a4549
 
c319a1e
33a4549
 
 
 
 
c319a1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48a2803
c319a1e
 
31df7d3
 
 
 
 
 
c319a1e
 
31df7d3
 
 
 
 
 
 
 
 
 
 
 
c319a1e
 
31df7d3
 
 
c319a1e
 
31df7d3
 
c319a1e
 
 
 
 
48a2803
33a4549
31df7d3
33a4549
c319a1e
33a4549
48a2803
 
 
33a4549
c319a1e
31df7d3
c319a1e
48a2803
 
 
31df7d3
48a2803
 
33a4549
48a2803
c319a1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33a4549
31df7d3
33a4549
48a2803
33a4549
 
31df7d3
 
 
 
 
 
33a4549
 
c58a978
33a4549
c319a1e
 
48a2803
33a4549
1353a1f
33a4549
342fd5f
 
 
3b0bca5
342fd5f
 
3b0bca5
 
342fd5f
 
 
 
3e4bf85
 
342fd5f
 
 
 
 
 
 
3e4bf85
342fd5f
 
3e4bf85
342fd5f
 
 
 
 
3e4bf85
 
 
342fd5f
be852d2
3b0bca5
be852d2
342fd5f
 
 
 
3b0bca5
 
 
 
342fd5f
 
 
 
 
 
 
 
be852d2
 
3778f9f
 
 
 
 
 
56bc4cf
3b0bca5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3778f9f
3b0bca5
be852d2
3778f9f
7a4bde2
3b0bca5
be852d2
 
 
 
 
7a4bde2
be852d2
 
 
3b0bca5
be852d2
3b0bca5
be852d2
3b0bca5
 
 
 
 
 
 
 
be852d2
 
 
3b0bca5
be852d2
3b0bca5
be852d2
 
3b0bca5
 
 
 
 
 
be852d2
 
3e4bf85
3b0bca5
 
 
 
 
3778f9f
 
 
8e384aa
be852d2
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
import os
import sys
import tempfile
import time
import itertools
import streamlit as st
import pandas as pd
import requests
import openai
from threading import Thread

# Add 'src' to Python path
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
from main import run_pipeline

st.set_page_config(page_title="πŸ“° AI News Analyzer", layout="wide")
st.title("🧠 AI-Powered Investing News Analyzer")

# === API Key Input ===
st.subheader("πŸ” API Keys")
openai_api_key = st.text_input("OpenAI API Key", type="password").strip()
tavily_api_key = st.text_input("Tavily API Key", type="password").strip()

# === Topic Input ===
st.subheader("πŸ“ˆ Topics of Interest")
topics_data = []
with st.form("topics_form"):
    topic_count = st.number_input("How many topics?", min_value=1, max_value=10, value=1, step=1)
    for i in range(topic_count):
        col1, col2 = st.columns(2)
        with col1:
            topic = st.text_input(f"Topic {i+1}", key=f"topic_{i}")
        with col2:
            days = st.number_input(f"Timespan (days)", min_value=1, max_value=30, value=7, key=f"days_{i}")
        topics_data.append({"topic": topic, "timespan_days": days})
    submitted = st.form_submit_button("Run Analysis")

# === Tabs Setup ===
tab_report, tab_articles, tab_insights = st.tabs(["πŸ“ Report", "πŸ“‹ Articles", "πŸ“Š Insights"])

if submitted:
    if not openai_api_key or not tavily_api_key or not all([td['topic'] for td in topics_data]):
        st.warning("Please fill in all fields.")
    else:
        # Reset old results
        articles_df = pd.DataFrame()
        insights_df = pd.DataFrame()
        html_paths = []

        os.environ["OPENAI_API_KEY"] = openai_api_key
        os.environ["TAVILY_API_KEY"] = tavily_api_key

        df = pd.DataFrame(topics_data)
        with tempfile.NamedTemporaryFile(delete=False, suffix=".csv") as tmp_csv:
            df.to_csv(tmp_csv.name, index=False)
            csv_path = tmp_csv.name

        spinner_box = st.empty()
        log_box = st.empty()
        logs = []
        rotating = True

        def log(msg):
            logs.append(msg)
            log_box.code("\n".join(logs))

        # === Rotating UI Messages ===
        def rotating_messages():
            messages = itertools.cycle([
                "πŸ” Searching financial news...",
                "🧠 Running AI analysis...",
                "πŸ“Š Evaluating sentiment...",
                "πŸ“ Generating report...",
                "πŸ’Ή Finalizing insights..."
            ])
            while rotating:
                spinner_box.markdown(f"⏳ {next(messages)}")
                time.sleep(1.5)

        rotator_thread = Thread(target=rotating_messages)
        rotator_thread.start()

        try:
            # Check API Keys
            try:
                client = openai.OpenAI(api_key=openai_api_key)
                client.models.list()
                log("βœ… OpenAI API key is valid.")
            except Exception as e:
                log(f"❌ OpenAI API Key Error: {e}")
                rotating = False
                rotator_thread.join()
                st.stop()

            try:
                response = requests.post(
                    "https://api.tavily.com/search",
                    headers={"Authorization": f"Bearer {tavily_api_key}"},
                    json={"query": "test", "days": 1, "max_results": 1}
                )
                if response.status_code == 200:
                    log("βœ… Tavily API key is valid.")
                else:
                    log(f"❌ Tavily Key Error: {response.status_code} {response.text}")
                    rotating = False
                    rotator_thread.join()
                    st.stop()
            except Exception as e:
                log(f"❌ Tavily API Key Error: {e}")
                rotating = False
                rotator_thread.join()
                st.stop()

            with st.spinner("⏳ Running analysis..."):
                html_paths, articles_df, insights_df = run_pipeline(csv_path, tavily_api_key, progress_callback=log)

            rotating = False
            rotator_thread.join()
            spinner_box.success("βœ… Analysis complete!")

            # === Report Tab ===
            with tab_report:
                st.subheader("πŸ“ Latest Report")
                if html_paths:
                    latest_report = html_paths[-1]
                    with open(latest_report, 'r', encoding='utf-8') as f:
                        html_content = f.read()

                    # Download button for HTML report
                    st.download_button(
                        label="⬇️ Download Report (HTML)",
                        data=html_content,
                        file_name=os.path.basename(latest_report),
                        mime="text/html"
                    )

                    st.components.v1.html(html_content, height=600, scrolling=True)
                else:
                    st.error("❌ No reports were generated.")

            # === Articles Tab ===
            with tab_articles:
                st.subheader("πŸ“‹ Articles Table")
                if not articles_df.empty:
                    st.dataframe(
                        articles_df[["Title", "URL", "Priority", "Sentiment", "Confidence", "Signal", "Date"]],
                        use_container_width=True
                    )
                    st.download_button(
                        label="⬇️ Download Articles CSV",
                        data=articles_df.to_csv(index=False).encode("utf-8"),
                        file_name="articles.csv",
                        mime="text/csv"
                    )
                else:
                    st.info("No articles available.")

            # === Insights Tab ===
            with tab_insights:
                st.subheader("πŸ“Š Investment Insights")
                if not insights_df.empty:
                    st.dataframe(insights_df, use_container_width=True)
                    st.download_button(
                        label="⬇️ Download Insights CSV",
                        data=insights_df.to_csv(index=False).encode("utf-8"),
                        file_name="insights.csv",
                        mime="text/csv"
                    )
                else:
                    st.info("No insights available.")

        except Exception as e:
            rotating = False
            rotator_thread.join()
            spinner_box.error("❌ Failed.")
            log_box.error(f"❌ Error: {e}")


# import os
# import sys
# import tempfile
# import time
# import streamlit as st
# import pandas as pd
# import requests
# import openai

# sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
# from main import run_pipeline

# st.set_page_config(page_title="πŸ“° AI News Analyzer", layout="wide")
# st.title("🧠 AI-Powered Investing News Analyzer")

# # === API Key Input ===
# st.subheader("πŸ” API Keys")
# openai_api_key = st.text_input("OpenAI API Key", type="password").strip()
# tavily_api_key = st.text_input("Tavily API Key", type="password").strip()

# # === Topic Input ===
# st.subheader("πŸ“ˆ Topics of Interest")
# topics_data = []
# with st.form("topics_form"):
#     topic_count = st.number_input("How many topics?", min_value=1, max_value=10, value=1, step=1)
#     for i in range(topic_count):
#         col1, col2 = st.columns(2)
#         with col1:
#             topic = st.text_input(f"Topic {i+1}", key=f"topic_{i}")
#         with col2:
#             days = st.number_input(f"Timespan (days)", min_value=1, max_value=30, value=7, key=f"days_{i}")
#         topics_data.append({"topic": topic, "timespan_days": days})
#     submitted = st.form_submit_button("Run Analysis")

# # === Tabs Setup ===
# tab_report, tab_articles, tab_insights, tab_debug = st.tabs(["πŸ“ Report", "πŸ“‹ Articles", "πŸ“Š Insights", "πŸ›  Debug"])

# if submitted:
#     if not openai_api_key or not tavily_api_key or not all([td['topic'] for td in topics_data]):
#         st.warning("Please fill in all fields.")
#     else:
#         articles_df = pd.DataFrame()
#         insights_df = pd.DataFrame()
#         html_paths = []

#         os.environ["OPENAI_API_KEY"] = openai_api_key
#         os.environ["TAVILY_API_KEY"] = tavily_api_key

#         df = pd.DataFrame(topics_data)
#         with tempfile.NamedTemporaryFile(delete=False, suffix=".csv") as tmp_csv:
#             df.to_csv(tmp_csv.name, index=False)
#             csv_path = tmp_csv.name

#         spinner_box = st.empty()
#         log_box = st.empty()
#         logs = []

#         def log(msg):
#             logs.append(msg)
#             log_box.code("\n".join(logs))

#         try:
#             spinner_box.markdown("⏳ Checking API keys...")

#             # === Check OpenAI Key ===
#             try:
#                 client = openai.OpenAI(api_key=openai_api_key)
#                 client.models.list()
#                 log("βœ… OpenAI API key is valid.")
#             except Exception as e:
#                 log(f"❌ OpenAI API Key Error: {e}")
#                 st.stop()

#             # === Check Tavily Key ===
#             try:
#                 response = requests.post(
#                     "https://api.tavily.com/search",
#                     headers={"Authorization": f"Bearer {tavily_api_key}"},
#                     json={"query": "test", "days": 1, "max_results": 1}
#                 )
#                 if response.status_code == 200:
#                     log("βœ… Tavily API key is valid.")
#                 else:
#                     log(f"❌ Tavily Key Error: {response.status_code} {response.text}")
#                     st.stop()
#             except Exception as e:
#                 log(f"❌ Tavily API Key Error: {e}")
#                 st.stop()

#             spinner_box.markdown("⏳ Running analysis pipeline...")
#             html_paths, articles_df, insights_df = run_pipeline(csv_path, tavily_api_key, progress_callback=log)
#             spinner_box.success("βœ… Analysis complete!")

#             # === Report Tab ===
#             with tab_report:
#                 if html_paths:
#                     for path in html_paths:
#                         with open(path, 'r', encoding='utf-8') as f:
#                             html_content = f.read()
#                             st.components.v1.html(html_content, height=600, scrolling=True)
#                 else:
#                     st.error("❌ No reports were generated.")

#             # === Articles Tab ===
#             with tab_articles:
#                 st.subheader("πŸ“‹ Articles Table")
#                 if not articles_df.empty:
#                     st.dataframe(articles_df[["Title", "URL", "Summary", "Priority", "Sentiment", "Confidence", "Signal", "Date"]],
#                                  use_container_width=True)
#                     st.download_button(
#                         label="⬇️ Download Articles CSV",
#                         data=articles_df.to_csv(index=False).encode("utf-8"),
#                         file_name="articles.csv",
#                         mime="text/csv"
#                     )
#                 else:
#                     st.info("No articles available.")

#             # === Insights Tab ===
#             with tab_insights:
#                 st.subheader("πŸ“Š Top Investment Insights")
#                 if not insights_df.empty:
#                     st.dataframe(insights_df, use_container_width=True)
#                     st.download_button(
#                         label="⬇️ Download Insights CSV",
#                         data=insights_df.to_csv(index=False).encode("utf-8"),
#                         file_name="insights.csv",
#                         mime="text/csv"
#                     )
#                 else:
#                     st.info("No insights available.")

#             # === Debug Tab ===
#             with tab_debug:
#                 st.subheader("πŸ›  Debug Log")
#                 st.code("\n".join(logs) if logs else "No logs yet.")

#         except Exception as e:
#             spinner_box.error("❌ Failed.")
#             log_box.error(f"❌ Error: {e}")