Spaces:
Runtime error
Runtime error
Sigrid De los Santos
commited on
Commit
Β·
0858d17
1
Parent(s):
be852d2
debugging
Browse files- app.py +9 -28
- src/main.py +33 -90
app.py
CHANGED
|
@@ -4,24 +4,23 @@ import tempfile
|
|
| 4 |
import streamlit as st
|
| 5 |
import pandas as pd
|
| 6 |
|
| 7 |
-
# Add 'src' to Python path
|
| 8 |
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
|
| 9 |
from main import run_pipeline
|
| 10 |
|
| 11 |
st.set_page_config(page_title="π° AI News Analyzer", layout="wide")
|
| 12 |
st.title("π§ AI-Powered Investing News Analyzer")
|
| 13 |
|
| 14 |
-
#
|
| 15 |
st.subheader("π API Keys")
|
| 16 |
openai_api_key = st.text_input("OpenAI API Key", type="password").strip()
|
| 17 |
tavily_api_key = st.text_input("Tavily API Key", type="password").strip()
|
| 18 |
|
| 19 |
-
#
|
| 20 |
st.subheader("π Topics of Interest")
|
| 21 |
topics_data = []
|
| 22 |
with st.form("topics_form"):
|
| 23 |
topic_count = st.number_input("How many topics?", min_value=1, max_value=10, value=1, step=1)
|
| 24 |
-
|
| 25 |
for i in range(topic_count):
|
| 26 |
col1, col2 = st.columns(2)
|
| 27 |
with col1:
|
|
@@ -29,23 +28,20 @@ with st.form("topics_form"):
|
|
| 29 |
with col2:
|
| 30 |
days = st.number_input(f"Timespan (days)", min_value=1, max_value=30, value=7, key=f"days_{i}")
|
| 31 |
topics_data.append({"topic": topic, "timespan_days": days})
|
| 32 |
-
|
| 33 |
submitted = st.form_submit_button("Run Analysis")
|
| 34 |
|
| 35 |
-
#
|
| 36 |
tab_report, tab_articles, tab_insights = st.tabs(["π Report", "π Articles", "π Insights"])
|
| 37 |
articles_df = pd.DataFrame()
|
| 38 |
insights_df = pd.DataFrame()
|
| 39 |
html_paths = []
|
| 40 |
|
| 41 |
-
# === Submission logic ===
|
| 42 |
if submitted:
|
| 43 |
if not openai_api_key or not tavily_api_key or not all([td['topic'] for td in topics_data]):
|
| 44 |
st.warning("Please fill in all fields.")
|
| 45 |
else:
|
| 46 |
os.environ["OPENAI_API_KEY"] = openai_api_key
|
| 47 |
os.environ["TAVILY_API_KEY"] = tavily_api_key
|
| 48 |
-
|
| 49 |
df = pd.DataFrame(topics_data)
|
| 50 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".csv") as tmp_csv:
|
| 51 |
df.to_csv(tmp_csv.name, index=False)
|
|
@@ -61,12 +57,10 @@ if submitted:
|
|
| 61 |
|
| 62 |
try:
|
| 63 |
spinner_box.markdown("β³ Running analysis pipeline...")
|
| 64 |
-
|
| 65 |
html_paths, articles_df, insights_df = run_pipeline(csv_path, tavily_api_key, progress_callback=log)
|
| 66 |
-
|
| 67 |
spinner_box.success("β
Analysis complete!")
|
| 68 |
|
| 69 |
-
#
|
| 70 |
with tab_report:
|
| 71 |
if html_paths:
|
| 72 |
for path in html_paths:
|
|
@@ -76,31 +70,18 @@ if submitted:
|
|
| 76 |
else:
|
| 77 |
st.error("β No reports were generated.")
|
| 78 |
|
| 79 |
-
#
|
| 80 |
with tab_articles:
|
| 81 |
-
st.subheader("π Articles Table")
|
| 82 |
if not articles_df.empty:
|
| 83 |
-
st.dataframe(articles_df,
|
| 84 |
-
|
| 85 |
-
label="β¬οΈ Download Articles CSV",
|
| 86 |
-
data=articles_df.to_csv(index=False).encode("utf-8"),
|
| 87 |
-
file_name="articles.csv",
|
| 88 |
-
mime="text/csv"
|
| 89 |
-
)
|
| 90 |
else:
|
| 91 |
st.info("No articles available.")
|
| 92 |
|
| 93 |
-
#
|
| 94 |
with tab_insights:
|
| 95 |
-
st.subheader("π Investment Insights")
|
| 96 |
if not insights_df.empty:
|
| 97 |
st.dataframe(insights_df, use_container_width=True)
|
| 98 |
-
st.download_button(
|
| 99 |
-
label="β¬οΈ Download Insights CSV",
|
| 100 |
-
data=insights_df.to_csv(index=False).encode("utf-8"),
|
| 101 |
-
file_name="insights.csv",
|
| 102 |
-
mime="text/csv"
|
| 103 |
-
)
|
| 104 |
else:
|
| 105 |
st.info("No insights available.")
|
| 106 |
|
|
|
|
| 4 |
import streamlit as st
|
| 5 |
import pandas as pd
|
| 6 |
|
| 7 |
+
# Add 'src' to Python path
|
| 8 |
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
|
| 9 |
from main import run_pipeline
|
| 10 |
|
| 11 |
st.set_page_config(page_title="π° AI News Analyzer", layout="wide")
|
| 12 |
st.title("π§ AI-Powered Investing News Analyzer")
|
| 13 |
|
| 14 |
+
# --- API Keys ---
|
| 15 |
st.subheader("π API Keys")
|
| 16 |
openai_api_key = st.text_input("OpenAI API Key", type="password").strip()
|
| 17 |
tavily_api_key = st.text_input("Tavily API Key", type="password").strip()
|
| 18 |
|
| 19 |
+
# --- Topics ---
|
| 20 |
st.subheader("π Topics of Interest")
|
| 21 |
topics_data = []
|
| 22 |
with st.form("topics_form"):
|
| 23 |
topic_count = st.number_input("How many topics?", min_value=1, max_value=10, value=1, step=1)
|
|
|
|
| 24 |
for i in range(topic_count):
|
| 25 |
col1, col2 = st.columns(2)
|
| 26 |
with col1:
|
|
|
|
| 28 |
with col2:
|
| 29 |
days = st.number_input(f"Timespan (days)", min_value=1, max_value=30, value=7, key=f"days_{i}")
|
| 30 |
topics_data.append({"topic": topic, "timespan_days": days})
|
|
|
|
| 31 |
submitted = st.form_submit_button("Run Analysis")
|
| 32 |
|
| 33 |
+
# --- Tabs ---
|
| 34 |
tab_report, tab_articles, tab_insights = st.tabs(["π Report", "π Articles", "π Insights"])
|
| 35 |
articles_df = pd.DataFrame()
|
| 36 |
insights_df = pd.DataFrame()
|
| 37 |
html_paths = []
|
| 38 |
|
|
|
|
| 39 |
if submitted:
|
| 40 |
if not openai_api_key or not tavily_api_key or not all([td['topic'] for td in topics_data]):
|
| 41 |
st.warning("Please fill in all fields.")
|
| 42 |
else:
|
| 43 |
os.environ["OPENAI_API_KEY"] = openai_api_key
|
| 44 |
os.environ["TAVILY_API_KEY"] = tavily_api_key
|
|
|
|
| 45 |
df = pd.DataFrame(topics_data)
|
| 46 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".csv") as tmp_csv:
|
| 47 |
df.to_csv(tmp_csv.name, index=False)
|
|
|
|
| 57 |
|
| 58 |
try:
|
| 59 |
spinner_box.markdown("β³ Running analysis pipeline...")
|
|
|
|
| 60 |
html_paths, articles_df, insights_df = run_pipeline(csv_path, tavily_api_key, progress_callback=log)
|
|
|
|
| 61 |
spinner_box.success("β
Analysis complete!")
|
| 62 |
|
| 63 |
+
# Report Tab
|
| 64 |
with tab_report:
|
| 65 |
if html_paths:
|
| 66 |
for path in html_paths:
|
|
|
|
| 70 |
else:
|
| 71 |
st.error("β No reports were generated.")
|
| 72 |
|
| 73 |
+
# Articles Tab
|
| 74 |
with tab_articles:
|
|
|
|
| 75 |
if not articles_df.empty:
|
| 76 |
+
st.dataframe(articles_df[["Title", "URL", "Summary", "Priority", "Date"]],
|
| 77 |
+
use_container_width=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
else:
|
| 79 |
st.info("No articles available.")
|
| 80 |
|
| 81 |
+
# Insights Tab
|
| 82 |
with tab_insights:
|
|
|
|
| 83 |
if not insights_df.empty:
|
| 84 |
st.dataframe(insights_df, use_container_width=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
else:
|
| 86 |
st.info("No insights available.")
|
| 87 |
|
src/main.py
CHANGED
|
@@ -9,27 +9,14 @@ from fin_interpreter import analyze_article
|
|
| 9 |
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
|
| 10 |
DATA_DIR = os.path.join(BASE_DIR, "data")
|
| 11 |
HTML_DIR = os.path.join(BASE_DIR, "html")
|
| 12 |
-
CSV_PATH = os.path.join(BASE_DIR, "investing_topics.csv")
|
| 13 |
|
| 14 |
os.makedirs(DATA_DIR, exist_ok=True)
|
| 15 |
os.makedirs(HTML_DIR, exist_ok=True)
|
| 16 |
|
| 17 |
load_dotenv()
|
| 18 |
|
| 19 |
-
|
| 20 |
-
def build_metrics_box(topic, num_articles):
|
| 21 |
-
now = datetime.now().strftime("%Y-%m-%d %H:%M")
|
| 22 |
-
return f"""
|
| 23 |
-
> Topic: `{topic}`
|
| 24 |
-
> Articles Collected: `{num_articles}`
|
| 25 |
-
> Generated: `{now}`
|
| 26 |
-
>
|
| 27 |
-
"""
|
| 28 |
-
|
| 29 |
-
|
| 30 |
def derive_priority(sentiment, confidence):
|
| 31 |
-
""
|
| 32 |
-
if sentiment == "Positive" and confidence > 0.75:
|
| 33 |
return "High"
|
| 34 |
elif sentiment == "Negative" and confidence > 0.6:
|
| 35 |
return "High"
|
|
@@ -37,141 +24,97 @@ def derive_priority(sentiment, confidence):
|
|
| 37 |
return "Medium"
|
| 38 |
return "Low"
|
| 39 |
|
| 40 |
-
|
| 41 |
-
def derive_signal(sentiment, confidence):
|
| 42 |
-
"""Basic investment signal logic."""
|
| 43 |
-
if sentiment == "Positive" and confidence > 0.7:
|
| 44 |
-
return "Buy"
|
| 45 |
-
elif sentiment == "Negative":
|
| 46 |
-
return "Avoid"
|
| 47 |
-
else:
|
| 48 |
-
return "Watch"
|
| 49 |
-
|
| 50 |
-
|
| 51 |
def run_value_investing_analysis(csv_path, progress_callback=None):
|
| 52 |
current_df = pd.read_csv(csv_path)
|
| 53 |
-
new_md_files = []
|
| 54 |
all_articles = []
|
|
|
|
| 55 |
|
| 56 |
for _, row in current_df.iterrows():
|
| 57 |
topic = row.get("topic")
|
| 58 |
timespan = row.get("timespan_days", 7)
|
| 59 |
-
msg = f"π Processing: {topic} ({timespan} days)"
|
| 60 |
-
print(msg)
|
| 61 |
if progress_callback:
|
| 62 |
-
progress_callback(
|
| 63 |
|
| 64 |
news = fetch_deep_news(topic, timespan)
|
| 65 |
if not news:
|
| 66 |
-
warning = f"β οΈ No news found for: {topic}"
|
| 67 |
-
if progress_callback:
|
| 68 |
-
progress_callback(warning)
|
| 69 |
continue
|
| 70 |
|
| 71 |
-
# Process each article
|
| 72 |
for article in news:
|
| 73 |
summary = article.get("summary", "")
|
| 74 |
title = article.get("title", "Untitled")
|
| 75 |
url = article.get("url", "")
|
| 76 |
date = article.get("date", datetime.now().strftime("%Y-%m-%d"))
|
| 77 |
-
company = article.get("company", topic)
|
| 78 |
|
| 79 |
try:
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
sentiment, confidence, signal = res[0], float(res[1]), res[2]
|
| 87 |
-
except Exception:
|
| 88 |
-
sentiment, confidence, signal = "Neutral", 0.0, "Watch"
|
| 89 |
|
| 90 |
priority = derive_priority(sentiment, confidence)
|
| 91 |
-
if signal == "None":
|
| 92 |
-
signal = derive_signal(sentiment, confidence)
|
| 93 |
|
|
|
|
| 94 |
all_articles.append({
|
| 95 |
"Title": title,
|
| 96 |
"URL": url,
|
| 97 |
"Summary": summary,
|
| 98 |
"Priority": priority,
|
| 99 |
"Date": date,
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
"Sentiment": sentiment,
|
| 102 |
-
"Confidence":
|
| 103 |
-
"
|
| 104 |
})
|
| 105 |
|
| 106 |
-
#
|
| 107 |
report_body = generate_value_investor_report(topic, news)
|
| 108 |
-
metrics_md = build_metrics_box(topic, len(news))
|
| 109 |
-
full_md = metrics_md + report_body
|
| 110 |
-
|
| 111 |
filename = f"{topic.replace(' ', '_').lower()}_{datetime.now().strftime('%Y-%m-%d')}.md"
|
| 112 |
filepath = os.path.join(DATA_DIR, filename)
|
| 113 |
-
counter = 1
|
| 114 |
-
while os.path.exists(filepath):
|
| 115 |
-
filename = f"{topic.replace(' ', '_').lower()}_{datetime.now().strftime('%Y-%m-%d')}_{counter}.md"
|
| 116 |
-
filepath = os.path.join(DATA_DIR, filename)
|
| 117 |
-
counter += 1
|
| 118 |
-
|
| 119 |
with open(filepath, "w", encoding="utf-8") as f:
|
| 120 |
-
f.write(
|
| 121 |
-
|
| 122 |
-
new_md_files.append(filepath)
|
| 123 |
-
|
| 124 |
-
return new_md_files, all_articles
|
| 125 |
|
|
|
|
| 126 |
|
| 127 |
-
def build_company_insights(
|
| 128 |
-
if
|
| 129 |
return pd.DataFrame()
|
| 130 |
|
|
|
|
| 131 |
insights = []
|
| 132 |
-
for company, group in
|
| 133 |
mentions = len(group)
|
| 134 |
dominant_sentiment = group["Sentiment"].mode()[0] if not group["Sentiment"].mode().empty else "Neutral"
|
| 135 |
-
dominant_signal = group["Signal"].mode()[0] if not group["Signal"].mode().empty else "Watch"
|
| 136 |
avg_confidence = round(group["Confidence"].mean(), 2)
|
| 137 |
-
risk_level = "High" if (dominant_sentiment == "Negative" and avg_confidence > 0.5) else "Low"
|
| 138 |
-
if dominant_sentiment == "Neutral":
|
| 139 |
-
risk_level = "Medium"
|
| 140 |
-
|
| 141 |
highlights = " | ".join(group["Summary"].head(2).tolist())
|
| 142 |
insights.append({
|
| 143 |
"Company": company,
|
| 144 |
"Mentions": mentions,
|
| 145 |
"Sentiment": dominant_sentiment,
|
| 146 |
-
"Signal": dominant_signal,
|
| 147 |
-
"Risk": risk_level,
|
| 148 |
"Confidence": avg_confidence,
|
| 149 |
"Highlights": highlights
|
| 150 |
})
|
| 151 |
-
|
| 152 |
return pd.DataFrame(insights)
|
| 153 |
|
| 154 |
-
|
| 155 |
def run_pipeline(csv_path, tavily_api_key, progress_callback=None):
|
| 156 |
os.environ["TAVILY_API_KEY"] = tavily_api_key
|
|
|
|
| 157 |
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
for
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
|
| 165 |
articles_df = pd.DataFrame(all_articles)
|
| 166 |
-
insights_df = build_company_insights(
|
| 167 |
-
return
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
if __name__ == "__main__":
|
| 171 |
-
md_files, all_articles = run_value_investing_analysis(CSV_PATH)
|
| 172 |
-
for md in md_files:
|
| 173 |
-
convert_md_to_html(md, HTML_DIR)
|
| 174 |
-
print(f"π All reports converted to HTML at: {HTML_DIR}")
|
| 175 |
|
| 176 |
|
| 177 |
# import os
|
|
|
|
| 9 |
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
|
| 10 |
DATA_DIR = os.path.join(BASE_DIR, "data")
|
| 11 |
HTML_DIR = os.path.join(BASE_DIR, "html")
|
|
|
|
| 12 |
|
| 13 |
os.makedirs(DATA_DIR, exist_ok=True)
|
| 14 |
os.makedirs(HTML_DIR, exist_ok=True)
|
| 15 |
|
| 16 |
load_dotenv()
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
def derive_priority(sentiment, confidence):
|
| 19 |
+
if sentiment == "Positive" and confidence > 0.7:
|
|
|
|
| 20 |
return "High"
|
| 21 |
elif sentiment == "Negative" and confidence > 0.6:
|
| 22 |
return "High"
|
|
|
|
| 24 |
return "Medium"
|
| 25 |
return "Low"
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
def run_value_investing_analysis(csv_path, progress_callback=None):
|
| 28 |
current_df = pd.read_csv(csv_path)
|
|
|
|
| 29 |
all_articles = []
|
| 30 |
+
company_data = []
|
| 31 |
|
| 32 |
for _, row in current_df.iterrows():
|
| 33 |
topic = row.get("topic")
|
| 34 |
timespan = row.get("timespan_days", 7)
|
|
|
|
|
|
|
| 35 |
if progress_callback:
|
| 36 |
+
progress_callback(f"π Processing: {topic} ({timespan} days)")
|
| 37 |
|
| 38 |
news = fetch_deep_news(topic, timespan)
|
| 39 |
if not news:
|
|
|
|
|
|
|
|
|
|
| 40 |
continue
|
| 41 |
|
|
|
|
| 42 |
for article in news:
|
| 43 |
summary = article.get("summary", "")
|
| 44 |
title = article.get("title", "Untitled")
|
| 45 |
url = article.get("url", "")
|
| 46 |
date = article.get("date", datetime.now().strftime("%Y-%m-%d"))
|
|
|
|
| 47 |
|
| 48 |
try:
|
| 49 |
+
result = analyze_article(summary)
|
| 50 |
+
sentiment = result.get("sentiment", "Neutral")
|
| 51 |
+
confidence = float(result.get("confidence", 0.0))
|
| 52 |
+
except Exception as e:
|
| 53 |
+
print(f"[FinBERT ERROR] {e}")
|
| 54 |
+
sentiment, confidence = "Neutral", 0.0
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
priority = derive_priority(sentiment, confidence)
|
|
|
|
|
|
|
| 57 |
|
| 58 |
+
# Add to articles_df
|
| 59 |
all_articles.append({
|
| 60 |
"Title": title,
|
| 61 |
"URL": url,
|
| 62 |
"Summary": summary,
|
| 63 |
"Priority": priority,
|
| 64 |
"Date": date,
|
| 65 |
+
})
|
| 66 |
+
|
| 67 |
+
# Collect company-level data for insights
|
| 68 |
+
company_data.append({
|
| 69 |
+
"Company": topic, # For now, use topic as company proxy
|
| 70 |
"Sentiment": sentiment,
|
| 71 |
+
"Confidence": confidence,
|
| 72 |
+
"Summary": summary,
|
| 73 |
})
|
| 74 |
|
| 75 |
+
# Save markdown report
|
| 76 |
report_body = generate_value_investor_report(topic, news)
|
|
|
|
|
|
|
|
|
|
| 77 |
filename = f"{topic.replace(' ', '_').lower()}_{datetime.now().strftime('%Y-%m-%d')}.md"
|
| 78 |
filepath = os.path.join(DATA_DIR, filename)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
with open(filepath, "w", encoding="utf-8") as f:
|
| 80 |
+
f.write(report_body)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
+
return all_articles, company_data
|
| 83 |
|
| 84 |
+
def build_company_insights(company_data):
|
| 85 |
+
if not company_data:
|
| 86 |
return pd.DataFrame()
|
| 87 |
|
| 88 |
+
df = pd.DataFrame(company_data)
|
| 89 |
insights = []
|
| 90 |
+
for company, group in df.groupby("Company"):
|
| 91 |
mentions = len(group)
|
| 92 |
dominant_sentiment = group["Sentiment"].mode()[0] if not group["Sentiment"].mode().empty else "Neutral"
|
|
|
|
| 93 |
avg_confidence = round(group["Confidence"].mean(), 2)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
highlights = " | ".join(group["Summary"].head(2).tolist())
|
| 95 |
insights.append({
|
| 96 |
"Company": company,
|
| 97 |
"Mentions": mentions,
|
| 98 |
"Sentiment": dominant_sentiment,
|
|
|
|
|
|
|
| 99 |
"Confidence": avg_confidence,
|
| 100 |
"Highlights": highlights
|
| 101 |
})
|
|
|
|
| 102 |
return pd.DataFrame(insights)
|
| 103 |
|
|
|
|
| 104 |
def run_pipeline(csv_path, tavily_api_key, progress_callback=None):
|
| 105 |
os.environ["TAVILY_API_KEY"] = tavily_api_key
|
| 106 |
+
all_articles, company_data = run_value_investing_analysis(csv_path, progress_callback)
|
| 107 |
|
| 108 |
+
# Convert markdown to HTML
|
| 109 |
+
html_paths = []
|
| 110 |
+
for md_file in os.listdir(DATA_DIR):
|
| 111 |
+
if md_file.endswith(".md"):
|
| 112 |
+
convert_md_to_html(os.path.join(DATA_DIR, md_file), HTML_DIR)
|
| 113 |
+
html_paths.append(os.path.join(HTML_DIR, md_file.replace(".md", ".html")))
|
| 114 |
|
| 115 |
articles_df = pd.DataFrame(all_articles)
|
| 116 |
+
insights_df = build_company_insights(company_data)
|
| 117 |
+
return html_paths, articles_df, insights_df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
|
| 120 |
# import os
|