Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,130 +1,209 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
|
| 3 |
-
"""
|
| 4 |
-
Streamlit application for Image-to-Story demo with history sidebar.
|
| 5 |
-
Allows demo/upload image, generates a caption, a trimmed story,
|
| 6 |
-
and plays back as MP3 via gTTS. Keeps history of all runs.
|
| 7 |
-
"""
|
| 8 |
import streamlit as st
|
| 9 |
-
|
| 10 |
-
import
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
import
|
| 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 |
-
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|
| 3 |
+
import uuid
|
| 4 |
+
import modules
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from sentence_transformers import SentenceTransformer
|
| 9 |
+
import faiss
|
| 10 |
+
from transformers import AutoTokenizer, AutoModelForTokenClassification
|
| 11 |
+
|
| 12 |
+
# βββ LOAD DATA & MODELS (unchanged) βββββββββββββββββββββββββββββββββββββββββ
|
| 13 |
+
df_etf, df_analyst_report, available_tickers, df_annual_return_master = modules.load_etf_data()
|
| 14 |
+
|
| 15 |
+
repo_name = "hskwon7/paraphrase-MiniLM-L6-v2-ft-for-etf-semantic-search"
|
| 16 |
+
s2_model = SentenceTransformer(repo_name)
|
| 17 |
+
df_etf["doc"] = df_etf.apply(modules.make_doc_text, axis=1)
|
| 18 |
+
etf_list = df_etf["ticker"].tolist()
|
| 19 |
+
doc_embs = s2_model.encode(df_etf["doc"].tolist(), convert_to_numpy=True, show_progress_bar=True)
|
| 20 |
+
faiss.normalize_L2(doc_embs)
|
| 21 |
+
index = faiss.IndexFlatIP(doc_embs.shape[1])
|
| 22 |
+
index.add(doc_embs)
|
| 23 |
+
|
| 24 |
+
def semantic_search(query, top_k=100):
|
| 25 |
+
q_emb = s2_model.encode([query], convert_to_numpy=True)
|
| 26 |
+
faiss.normalize_L2(q_emb)
|
| 27 |
+
D, I = index.search(q_emb, top_k)
|
| 28 |
+
return [(etf_list[idx], float(D[0][i])) for i, idx in enumerate(I[0])]
|
| 29 |
+
|
| 30 |
+
# NER ensemble remains the same
|
| 31 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 32 |
+
repo1 = "hskwon7/distilbert-base-uncased-for-etf-ticker"
|
| 33 |
+
repo2 = "hskwon7/albert-base-v2-for-etf-ticker"
|
| 34 |
+
tokenizer1 = AutoTokenizer.from_pretrained(repo1)
|
| 35 |
+
model1 = AutoModelForTokenClassification.from_pretrained(repo1).to(device).eval()
|
| 36 |
+
tokenizer2 = AutoTokenizer.from_pretrained(repo2)
|
| 37 |
+
model2 = AutoModelForTokenClassification.from_pretrained(repo2).to(device).eval()
|
| 38 |
+
valid_ticker_set = set(t.upper() for t in df_etf['ticker'].unique().tolist())
|
| 39 |
+
|
| 40 |
+
def ensemble_ticker_extraction(query):
|
| 41 |
+
preds = set()
|
| 42 |
+
for tok, mdl in ((tokenizer1, model1),(tokenizer2, model2)):
|
| 43 |
+
enc = tok(query, return_tensors="pt").to(device)
|
| 44 |
+
with torch.no_grad():
|
| 45 |
+
logits = mdl(**enc).logits
|
| 46 |
+
ids = logits.argmax(dim=-1)[0].tolist()
|
| 47 |
+
toks = tok.convert_ids_to_tokens(enc["input_ids"][0])
|
| 48 |
+
labs = [mdl.config.id2label[i] for i in ids]
|
| 49 |
+
preds |= modules.extract_valid_tickers(toks, labs, tok, valid_ticker_set)
|
| 50 |
+
return preds
|
| 51 |
+
|
| 52 |
+
# βββ HELPERS ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 53 |
+
|
| 54 |
+
def display_sample_query_box(task: str):
|
| 55 |
+
"""
|
| 56 |
+
Renders one sample-query box for the given task
|
| 57 |
+
and adds a 'Try this app' button that switches the sidebar page.
|
| 58 |
+
"""
|
| 59 |
+
sample_queries = {
|
| 60 |
+
"search_etf": {
|
| 61 |
+
"title": "ETF Search",
|
| 62 |
+
"description": "Explore ETFs based on dividend, expense ratio, sector, etc.",
|
| 63 |
+
"examples": ['Find me technology ETFs', 'Show me Cryptocurrency ETFs']
|
| 64 |
+
},
|
| 65 |
+
"comparison": {
|
| 66 |
+
"title": "ETF Comparison",
|
| 67 |
+
"description": "Compare two ETFs side by side on performance, risk, etc.",
|
| 68 |
+
"examples": ["QQQ vs. SPY", "Compare performance of QQQ with SPY"]
|
| 69 |
+
},
|
| 70 |
+
"portfolio_projection": {
|
| 71 |
+
"title": "ETF Portfolio",
|
| 72 |
+
"description": "Project a multi-ETF portfolio out over 30 years.",
|
| 73 |
+
"examples": ["SPY, GLD, BND", "I want to invest in SCHD and IAU"]
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
details = sample_queries[task]
|
| 77 |
+
box_html = f"""
|
| 78 |
+
<div style='border:1px solid #ddd;padding:1rem;border-radius:8px;'>
|
| 79 |
+
<h4>{details['title']}</h4>
|
| 80 |
+
<p style='color:#555;margin-bottom:.5rem;'>{details['description']}</p>
|
| 81 |
+
<p style='font-style:italic;color:#333;'>
|
| 82 |
+
Examples:<br/>{'<br/>'.join(details['examples'])}
|
| 83 |
+
</p>
|
| 84 |
+
</div>
|
| 85 |
+
"""
|
| 86 |
+
st.markdown(box_html, unsafe_allow_html=True)
|
| 87 |
+
if st.button("Try this app", key=f"try_{task}"):
|
| 88 |
+
page_map = {
|
| 89 |
+
"search_etf": "ETF Search",
|
| 90 |
+
"comparison": "ETF Comparison",
|
| 91 |
+
"portfolio_projection": "ETF Portfolio"
|
| 92 |
+
}
|
| 93 |
+
st.session_state["page"] = page_map[task]
|
| 94 |
+
st.experimental_rerun()
|
| 95 |
+
|
| 96 |
+
def display_chat_history(task: str):
|
| 97 |
+
"""
|
| 98 |
+
Shows only the chat history for a given task.
|
| 99 |
+
"""
|
| 100 |
+
hist = st.session_state.get(f"all_chat_history_{task}", [])
|
| 101 |
+
for entry in hist:
|
| 102 |
+
if task == "search_etf":
|
| 103 |
+
st.chat_message("assistant").write(entry["response"])
|
| 104 |
+
modules.display_matching_etfs(entry["df"])
|
| 105 |
+
elif task == "comparison":
|
| 106 |
+
st.chat_message("assistant").write(entry["response"])
|
| 107 |
+
st.plotly_chart(entry["fig"], use_container_width=True)
|
| 108 |
+
st.dataframe(entry["df"], hide_index=True)
|
| 109 |
+
elif task == "portfolio_projection":
|
| 110 |
+
st.chat_message("assistant").write(entry["response"])
|
| 111 |
+
st.plotly_chart(entry["fig"], use_container_width=True)
|
| 112 |
+
|
| 113 |
+
def process_query(task: str, query: str):
|
| 114 |
+
"""
|
| 115 |
+
Core logic for each sub-app.
|
| 116 |
+
"""
|
| 117 |
+
# make sure top_k / top_n are always available
|
| 118 |
+
top_k, top_n = 100, 30
|
| 119 |
+
|
| 120 |
+
if task == 'search_etf':
|
| 121 |
+
with st.spinner("Searching ETFs..."):
|
| 122 |
+
fetched = semantic_search(query, top_k=top_k)
|
| 123 |
+
df_out = modules.get_etf_recommendations_from_list(fetched,
|
| 124 |
+
modules.get_cols_to_display(), df_etf, top_n=top_n)
|
| 125 |
+
st.session_state[f"all_chat_history_{task}"].append(
|
| 126 |
+
modules.form_d_chat_history(
|
| 127 |
+
result_id=str(uuid.uuid4()),
|
| 128 |
+
response=f"{len(df_out)} ETFs found.",
|
| 129 |
+
task=task,
|
| 130 |
+
df=df_out
|
| 131 |
+
)
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
elif task == 'comparison':
|
| 135 |
+
with st.spinner("Running comparison..."):
|
| 136 |
+
tickers = ensemble_ticker_extraction(query)
|
| 137 |
+
if len(tickers) != 2:
|
| 138 |
+
response, fig, df_out = (
|
| 139 |
+
"Please specify exactly two tickers.", None, None
|
| 140 |
+
)
|
| 141 |
+
else:
|
| 142 |
+
df_out = modules.get_etf_recommendations_from_list(
|
| 143 |
+
[(t, None) for t in tickers],
|
| 144 |
+
modules.get_cols_to_display(), df_etf, top_n=2
|
| 145 |
+
)
|
| 146 |
+
fig = modules.compare_etfs_interactive(*tickers)
|
| 147 |
+
response = f"Compared {tickers[0]} vs. {tickers[1]}."
|
| 148 |
+
st.session_state[f"all_chat_history_{task}"].append(
|
| 149 |
+
modules.form_d_chat_history(
|
| 150 |
+
result_id=str(uuid.uuid4()),
|
| 151 |
+
response=response,
|
| 152 |
+
task=task,
|
| 153 |
+
fig=fig,
|
| 154 |
+
df=df_out
|
| 155 |
+
)
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
elif task == 'portfolio_projection':
|
| 159 |
+
with st.spinner("Projecting portfolio..."):
|
| 160 |
+
fetched = semantic_search(query, top_k=top_k)
|
| 161 |
+
df_port = modules.run_portfolio_analysis(fetched, df_etf, df_annual_return_master)
|
| 162 |
+
fig = modules.portfolio_interactive_chart(df_port)
|
| 163 |
+
response = "30-year projection generated."
|
| 164 |
+
st.session_state[f"all_chat_history_{task}"].append(
|
| 165 |
+
modules.form_d_chat_history(
|
| 166 |
+
result_id=str(uuid.uuid4()),
|
| 167 |
+
response=response,
|
| 168 |
+
task=task,
|
| 169 |
+
fig=fig
|
| 170 |
)
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
# βββ MAIN ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 174 |
+
st.set_page_config(layout="wide")
|
| 175 |
+
if "page" not in st.session_state:
|
| 176 |
+
st.session_state["page"] = "ETF Search" # default
|
| 177 |
+
|
| 178 |
+
# initialize histories
|
| 179 |
+
for t in ["search_etf","comparison","portfolio_projection"]:
|
| 180 |
+
st.session_state.setdefault(f"all_chat_history_{t}", [])
|
| 181 |
+
|
| 182 |
+
# sidebar navigation
|
| 183 |
+
st.sidebar.title("ETF Assistant")
|
| 184 |
+
st.sidebar.radio("Go toβ¦", ["ETF Search","ETF Comparison","ETF Portfolio"], key="page")
|
| 185 |
+
|
| 186 |
+
# dispatch
|
| 187 |
+
page = st.session_state["page"]
|
| 188 |
+
st.title(page)
|
| 189 |
+
|
| 190 |
+
if page == "ETF Search":
|
| 191 |
+
display_sample_query_box("search_etf")
|
| 192 |
+
display_chat_history("search_etf")
|
| 193 |
+
q = st.chat_input("Search for ETFsβ¦", key="in_search")
|
| 194 |
+
if q:
|
| 195 |
+
process_query("search_etf", q)
|
| 196 |
+
|
| 197 |
+
elif page == "ETF Comparison":
|
| 198 |
+
display_sample_query_box("comparison")
|
| 199 |
+
display_chat_history("comparison")
|
| 200 |
+
q = st.chat_input("Compare ETFsβ¦", key="in_comp")
|
| 201 |
+
if q:
|
| 202 |
+
process_query("comparison", q)
|
| 203 |
+
|
| 204 |
+
elif page == "ETF Portfolio":
|
| 205 |
+
display_sample_query_box("portfolio_projection")
|
| 206 |
+
display_chat_history("portfolio_projection")
|
| 207 |
+
q = st.chat_input("Project portfolioβ¦", key="in_port")
|
| 208 |
+
if q:
|
| 209 |
+
process_query("portfolio_projection", q)
|