-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
526 lines (462 loc) · 24.9 KB
/
Copy pathapp.py
File metadata and controls
526 lines (462 loc) · 24.9 KB
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
"""
Oil Intelligence Terminal — v4
Per-article Brent sentiment classification with structured rendering
"""
import streamlit as st
import subprocess
from collections import Counter
from datetime import datetime
import pandas as pd
st.set_page_config(page_title="Oil Intelligence", page_icon="🛢", layout="wide", initial_sidebar_state="collapsed")
# ── CSS ───────────────────────────────────────────────────────────────────────
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap');
html, body, [class*="css"] { font-family: 'IBM Plex Sans', sans-serif; background: #0a0a0a; color: #d8d0c0; }
.stApp { background: #0a0a0a; }
#MainMenu, footer, header { visibility: hidden; }
.block-container { padding: 1.5rem 2.5rem; max-width: 1200px; }
/* Header */
.hdr-title { font-family:'IBM Plex Mono',monospace; font-size:1rem; font-weight:500;
color:#f0a500; letter-spacing:0.15em; text-transform:uppercase; margin:0; }
.hdr-sub { font-family:'IBM Plex Mono',monospace; font-size:0.6rem; color:#333;
letter-spacing:0.08em; margin-top:0.2rem; }
/* Indicators */
.ind-strip { display:flex; gap:0.6rem; margin-bottom:1.5rem; }
.ind-card { flex:1; background:#0d0d0d; border:1px solid #181818; border-radius:2px;
padding:0.6rem 0.8rem; min-width:0; }
.ind-lbl { font-family:'IBM Plex Mono',monospace; font-size:0.5rem; color:#444;
letter-spacing:0.1em; text-transform:uppercase; white-space:nowrap;
overflow:hidden; text-overflow:ellipsis; }
.ind-val { font-family:'IBM Plex Mono',monospace; font-size:1.1rem; font-weight:600;
color:#f0a500; margin-top:0.15rem; }
.ind-chg { font-family:'IBM Plex Mono',monospace; font-size:0.55rem; color:#555;
margin-top:0.1rem; }
.ind-up { color:#4caf50; }
.ind-down { color:#ef5350; }
/* Tabs */
.stTabs [data-baseweb="tab-list"] { gap:0; border-bottom:1px solid #1a1a1a; background:transparent; }
.stTabs [data-baseweb="tab"] {
font-family:'IBM Plex Mono',monospace; font-size:0.6rem; letter-spacing:0.1em;
text-transform:uppercase; color:#444; background:transparent; border:none;
border-bottom:2px solid transparent; padding:0.6rem 1.2rem; }
.stTabs [aria-selected="true"] { color:#f0a500!important; border-bottom:2px solid #f0a500!important; background:transparent!important; }
/* Output boxes */
.out { background:#0d0d0d; border:1px solid #181818; border-left:3px solid #f0a500;
border-radius:2px; padding:1.2rem; font-size:0.82rem; line-height:1.65;
color:#bbb; margin-top:0.8rem; white-space:pre-wrap; }
.memo { background:#0d0d0d; border:1px solid #181818; border-left:3px solid #d8d0c0;
border-radius:2px; padding:1.5rem; font-size:0.82rem; line-height:1.7;
color:#bbb; margin-top:0.8rem; white-space:pre-wrap; }
.risk-out { background:#0d0d0d; border:1px solid #181818; border-left:3px solid #ef5350;
border-radius:2px; padding:1.2rem; font-size:0.82rem; line-height:1.65;
color:#bbb; margin-top:0.8rem; white-space:pre-wrap; }
/* Article cards (NEW) */
.article-card {
background:#0d0d0d; border:1px solid #181818; border-radius:2px;
padding:1rem 1.2rem; margin-top:0.6rem;
}
.article-headline {
font-family:'IBM Plex Sans',sans-serif; font-size:0.9rem; font-weight:500;
color:#e8e0d0; line-height:1.4; margin-bottom:0.4rem;
}
.article-event {
font-family:'IBM Plex Sans',sans-serif; font-size:0.75rem; color:#888;
line-height:1.5; margin-bottom:0.8rem;
}
.article-impact-row {
display:flex; gap:0.4rem; flex-wrap:wrap; margin-bottom:0.6rem;
}
.impact-pill {
font-family:'IBM Plex Mono',monospace; font-size:0.55rem; letter-spacing:0.08em;
text-transform:uppercase; padding:0.2rem 0.55rem; border-radius:2px;
border:1px solid; white-space:nowrap;
}
.impact-pill .lbl { color:#666; font-weight:400; margin-right:0.3rem; }
.imp-bullish { background:#001a08; border-color:#003a18; color:#4caf50; }
.imp-bearish { background:#1a0000; border-color:#3a0000; color:#ef5350; }
.imp-neutral { background:#0f0f0f; border-color:#222; color:#777; }
.imp-mixed { background:#1a1000; border-color:#3a2400; color:#ffa726; }
.article-reason {
font-size:0.72rem; color:#888; line-height:1.55; margin-top:0.5rem;
padding-top:0.5rem; border-top:1px solid #181818;
}
.article-meta {
display:flex; justify-content:space-between; align-items:center;
margin-top:0.6rem; font-family:'IBM Plex Mono',monospace; font-size:0.55rem;
color:#444;
}
.confidence-bar {
display:inline-block; width:80px; height:3px; background:#222;
border-radius:1px; overflow:hidden; vertical-align:middle; margin-left:0.4rem;
}
.confidence-fill { height:100%; background:#f0a500; }
/* Aggregate summary card */
.agg-card {
background:#0d0d0d; border:1px solid #181818; border-left:3px solid #f0a500;
border-radius:2px; padding:1.2rem; margin-bottom:1rem;
}
.agg-title { font-family:'IBM Plex Mono',monospace; font-size:0.6rem; color:#666;
letter-spacing:0.1em; text-transform:uppercase; margin-bottom:0.6rem; }
.agg-row { display:flex; gap:1.5rem; }
.agg-item { flex:1; }
.agg-count { font-family:'IBM Plex Mono',monospace; font-size:1.8rem; font-weight:600; }
.agg-label { font-family:'IBM Plex Mono',monospace; font-size:0.55rem;
letter-spacing:0.1em; text-transform:uppercase; color:#555;
margin-top:0.2rem; }
.agg-bullish { color:#4caf50; }
.agg-bearish { color:#ef5350; }
.agg-neutral { color:#777; }
.agg-mixed { color:#ffa726; }
/* Source cards */
.src-card { background:#0b0b0b; border:1px solid #151515; border-radius:2px;
padding:0.6rem 0.8rem; margin-top:0.4rem; }
.src-hdr { display:flex; justify-content:space-between; font-family:'IBM Plex Mono',monospace;
font-size:0.55rem; color:#555; }
.src-preview { color:#666; font-size:0.7rem; line-height:1.5; margin-top:0.3rem;
max-height:60px; overflow:hidden; }
.src-url { color:#4a9eff; font-size:0.55rem; word-break:break-all; text-decoration:none; }
/* Chips */
.chip { display:inline-block; font-family:'IBM Plex Mono',monospace; font-size:0.5rem;
letter-spacing:0.08em; text-transform:uppercase; padding:0.15rem 0.4rem;
border-radius:2px; margin-right:0.3rem; margin-top:0.6rem; }
.c-news { background:#1a1200; color:#f0a500; border:1px solid #2a1a00; }
.c-prices { background:#001a0a; color:#4caf50; border:1px solid #002a14; }
.c-eia { background:#001020; color:#4a9eff; border:1px solid #001a30; }
.c-eia_report { background:#001020; color:#4a9eff; border:1px solid #001a30; }
.c-opec { background:#1a000a; color:#f06292; border:1px solid #2a0014; }
/* Risk */
.sev-HIGH { background:#1a0000; color:#ff5252; padding:0.1rem 0.4rem; border:1px solid #330000;
border-radius:2px; font-size:0.5rem; font-family:'IBM Plex Mono',monospace; }
.sev-MEDIUM { background:#1a1000; color:#ffa726; padding:0.1rem 0.4rem; border:1px solid #332000;
border-radius:2px; font-size:0.5rem; font-family:'IBM Plex Mono',monospace; }
.sev-LOW { background:#111; color:#666; padding:0.1rem 0.4rem; border:1px solid #222;
border-radius:2px; font-size:0.5rem; font-family:'IBM Plex Mono',monospace; }
.rsk-card { background:#0d0d0d; border:1px solid #181818; border-radius:2px;
padding:0.6rem; text-align:center; }
.rsk-cnt { font-family:'IBM Plex Mono',monospace; font-size:1.3rem; font-weight:600;
margin-top:0.15rem; }
.rsk-active { color:#f0a500; }
.rsk-clear { color:#222; }
/* Eval */
.ev-card { background:#0d0d0d; border:1px solid #181818; border-radius:2px;
padding:0.8rem; text-align:center; }
.ev-lbl { font-family:'IBM Plex Mono',monospace; font-size:0.5rem; color:#444;
letter-spacing:0.1em; text-transform:uppercase; }
.ev-val { font-family:'IBM Plex Mono',monospace; font-size:1.6rem; font-weight:600;
margin-top:0.3rem; }
.ev-pass { color:#4caf50; } .ev-warn { color:#ffa726; } .ev-fail { color:#ef5350; }
/* Buttons */
.stButton > button {
font-family:'IBM Plex Mono',monospace; font-size:0.6rem; letter-spacing:0.1em;
text-transform:uppercase; background:transparent; border:1px solid #f0a500;
color:#f0a500; padding:0.4rem 1.2rem; border-radius:2px; }
.stButton > button:hover { background:#f0a500; color:#0a0a0a; }
.stTextInput > div > div > input, .stTextArea > div > div > textarea {
background:#0d0d0d; border:1px solid #181818; border-radius:2px;
color:#d8d0c0; font-family:'IBM Plex Mono',monospace; font-size:0.75rem; }
.lbl { font-family:'IBM Plex Mono',monospace; font-size:0.55rem; letter-spacing:0.1em;
text-transform:uppercase; color:#444; margin-bottom:0.3rem; }
hr { border-color:#141414; }
</style>
""", unsafe_allow_html=True)
# ── Loaders ───────────────────────────────────────────────────────────────────
@st.cache_resource(show_spinner="Loading Oil Intelligence...")
def load_rag():
from RAG import OilIntelligence
return OilIntelligence()
@st.cache_data(ttl=3600)
def load_indicators():
from indicators import all_indicators
return all_indicators()
@st.cache_data(ttl=3600)
def load_risk_scan():
from risk_and_eval import RiskIntelligence
return RiskIntelligence().scan_all()
def render_sources(sources: list[dict]):
types = sorted(set(s.get("source", "") for s in sources))
chips = "".join(f'<span class="chip c-{t}">{t.replace("_"," ")}</span>' for t in types)
st.markdown(f'<div>{chips}</div>', unsafe_allow_html=True)
st.markdown('<p class="lbl" style="margin-top:0.8rem;">Retrieved Sources</p>', unsafe_allow_html=True)
for i, s in enumerate(sources):
score = s.get("score", 0)
date = s.get("date", "")
url = s.get("url", "")
src = s.get("source", "").upper()
prev = s.get("text", "")[:300].replace("\n", " ")
with st.expander(f"📎 {i+1} · {src} · {date} · {score:.3f}", expanded=False):
if url:
st.markdown(f'<a class="src-url" href="{url}" target="_blank">{url}</a>', unsafe_allow_html=True)
st.markdown(f'<div class="src-preview">{prev}...</div>', unsafe_allow_html=True)
def render_article_classification(item: dict):
"""Render one classified article as a structured card."""
cls = item["classification"]
chunk = item["chunk"]
if cls.get("_parse_failed"):
st.markdown(f'''
<div class="article-card" style="border-left:3px solid #ef5350;">
<div class="article-headline">⚠️ Classifier Parse Failed</div>
<div class="article-event">{cls.get("_raw","")[:200]}</div>
</div>''', unsafe_allow_html=True)
return
# Build impact pills row
dimensions = [
("Supply", cls.get("supply_effect", "neutral")),
("Demand", cls.get("demand_effect", "neutral")),
("Geopolitical", cls.get("geopolitical_risk_effect", "neutral")),
("Short-Term", cls.get("short_term_brent_impact", "neutral")),
("Long-Term", cls.get("medium_long_term_brent_impact", "neutral")),
("Overall", cls.get("overall_brent_impact", "neutral")),
]
pills_html = ""
for label, value in dimensions:
v = value.lower() if isinstance(value, str) else "neutral"
pills_html += f'<span class="impact-pill imp-{v}"><span class="lbl">{label}</span>{v.upper()}</span>'
confidence = cls.get("confidence", 0)
if isinstance(confidence, str):
try: confidence = int(confidence)
except: confidence = 0
headline = cls.get("headline", "—")
event = cls.get("core_event", "")
reason = cls.get("reason", "")
url = chunk.get("url", "")
date = chunk.get("date", "")
st.markdown(f'''
<div class="article-card">
<div class="article-headline">{headline}</div>
<div class="article-event">{event}</div>
<div class="article-impact-row">{pills_html}</div>
<div class="article-reason">{reason}</div>
<div class="article-meta">
<span>{date}{" · " + url[:60] + "..." if url else ""}</span>
<span>CONFIDENCE: {confidence}
<span class="confidence-bar">
<span class="confidence-fill" style="width:{confidence}%;"></span>
</span>
</span>
</div>
</div>
''', unsafe_allow_html=True)
def render_aggregate(classifications: list[dict]):
"""Show counts of bullish/bearish/neutral/mixed across articles."""
overalls = [c["classification"].get("overall_brent_impact", "neutral").lower()
for c in classifications if not c["classification"].get("_parse_failed")]
counts = Counter(overalls)
items_html = ""
for label in ["bullish", "bearish", "mixed", "neutral"]:
count = counts.get(label, 0)
items_html += f'''
<div class="agg-item">
<div class="agg-count agg-{label}">{count}</div>
<div class="agg-label">{label}</div>
</div>'''
total = len(overalls)
# Determine net sentiment
if counts.get("bullish", 0) > counts.get("bearish", 0) * 1.5:
net = "NET BULLISH"
net_class = "agg-bullish"
elif counts.get("bearish", 0) > counts.get("bullish", 0) * 1.5:
net = "NET BEARISH"
net_class = "agg-bearish"
elif counts.get("mixed", 0) > total / 2:
net = "MIXED"
net_class = "agg-mixed"
else:
net = "BALANCED / NEUTRAL"
net_class = "agg-neutral"
st.markdown(f'''
<div class="agg-card">
<div class="agg-title">Brent Sentiment · {total} Articles Analyzed</div>
<div class="agg-row">{items_html}</div>
<div style="margin-top:0.8rem; font-family:'IBM Plex Mono',monospace; font-size:0.75rem;
letter-spacing:0.1em;" class="{net_class}">→ {net}</div>
</div>''', unsafe_allow_html=True)
# ── Header with refresh ──────────────────────────────────────────────────────
col_hdr, col_refresh = st.columns([8, 2])
with col_hdr:
st.markdown("""
<div>
<p class="hdr-title">🛢 Oil Intelligence Terminal</p>
<p class="hdr-sub">RAG · Brent Sentiment Classifier · EIA · NewsAPI · Risk Monitoring</p>
</div>""", unsafe_allow_html=True)
with col_refresh:
st.markdown("<div style='height:0.5rem;'></div>", unsafe_allow_html=True)
if st.button("🔄 Refresh Data", key="refresh"):
with st.spinner("Pulling fresh data, re-scraping, rebuilding index..."):
subprocess.run(["python", "day1_data_pipeline.py"], capture_output=True)
subprocess.run(["python", "scraper.py"], capture_output=True)
import RAG
RAG.build_index(force=True)
st.cache_data.clear()
st.cache_resource.clear()
st.rerun()
st.markdown('<hr style="margin:0.5rem 0 1rem 0;">', unsafe_allow_html=True)
# Indicators
indicators = load_indicators()
if indicators:
ind_html = '<div class="ind-strip">'
for ind in indicators[:6]:
trend_cls = "ind-up" if ind.get("trend") == "up" else "ind-down" if ind.get("trend") == "down" else ""
chg = f'<div class="ind-chg {trend_cls}">{ind.get("change","")}</div>' if ind.get("change") else ""
ind_html += f'''
<div class="ind-card">
<div class="ind-lbl">{ind["label"]}</div>
<div class="ind-val">{ind["value"]} <span style="font-size:0.55rem;color:#555;">{ind.get("unit","")}</span></div>
{chg}
</div>'''
ind_html += '</div>'
st.markdown(ind_html, unsafe_allow_html=True)
try:
oil = load_rag()
except Exception as e:
st.error(f"RAG init failed: {e}")
st.stop()
tab1, tab2, tab3, tab4, tab5 = st.tabs(["Brief", "Q&A", "Memo", "Deal Risk", "Eval"])
# ── TAB 1: Brent Sentiment Brief ─────────────────────────────────────────────
with tab1:
st.markdown('<p class="lbl">Brent Crude Sentiment Analysis</p>', unsafe_allow_html=True)
st.markdown('<p style="color:#555; font-size:0.7rem; margin-bottom:1rem;">'
'Per-article structured classification for front-month Brent price direction.</p>',
unsafe_allow_html=True)
if st.button("Run Brent Sentiment Analysis", key="news_btn"):
with st.spinner("Classifying articles across 6 dimensions each..."):
classifications, sources = oil.news_brief_classified()
if not classifications:
st.warning("No news articles found in corpus. Hit Refresh Data to pull fresh news.")
else:
# Aggregate summary
render_aggregate(classifications)
# Per-article cards
st.markdown('<p class="lbl" style="margin-top:1.2rem;">Article-Level Classifications</p>',
unsafe_allow_html=True)
for item in classifications:
render_article_classification(item)
# ── TAB 2: Q&A ───────────────────────────────────────────────────────────────
with tab2:
st.markdown('<p class="lbl">Ask the Data</p>', unsafe_allow_html=True)
presets = [
"Current US crude inventory?",
"WTI price trend last month?",
"Key supply risks now?",
"WTI-Brent spread?",
]
pcols = st.columns(len(presets))
selected = None
for i, (c, p) in enumerate(zip(pcols, presets)):
with c:
if st.button(p, key=f"p_{i}"):
selected = p
question = st.text_input("q", value=selected or "", placeholder="Ask anything about oil markets...", label_visibility="collapsed")
if st.button("Ask", key="ask_btn") and question:
with st.spinner("Retrieving..."):
answer, sources = oil.ask_with_sources(question)
st.markdown(f'<div class="out">{answer}</div>', unsafe_allow_html=True)
render_sources(sources)
# ── TAB 3: Memo ──────────────────────────────────────────────────────────────
with tab3:
st.markdown('<p class="lbl">Investment Memo Generator</p>', unsafe_allow_html=True)
memo_topic = st.text_input("mt", placeholder="e.g. WTI Q3 2026 outlook / OPEC production cuts / shale thesis", label_visibility="collapsed")
if st.button("Generate Memo", key="memo_btn") and memo_topic:
with st.spinner("Generating..."):
answer, sources = oil.memo_with_sources(memo_topic)
st.markdown(f'''
<div style="font-family:IBM Plex Mono,monospace; font-size:0.55rem; color:#333;
letter-spacing:0.08em; margin-top:1rem;">
INVESTMENT MEMORANDUM · {datetime.now().strftime("%B %d, %Y").upper()}
</div>''', unsafe_allow_html=True)
st.markdown(f'<div class="memo">{answer}</div>', unsafe_allow_html=True)
st.download_button(
"Download .txt",
data=f"INVESTMENT MEMORANDUM\n{datetime.now().strftime('%B %d, %Y')}\nTopic: {memo_topic}\n\n{answer}",
file_name=f"memo_{datetime.now().strftime('%Y%m%d')}.txt", mime="text/plain",
)
render_sources(sources)
# ── TAB 4: Deal Risk ─────────────────────────────────────────────────────────
with tab4:
st.markdown('<p class="lbl">Risk Monitor</p>', unsafe_allow_html=True)
risk_report = load_risk_scan()
cat_html = '<div style="display:flex; gap:0.5rem; margin-bottom:1.2rem;">'
for cat in risk_report["categories"]:
cnt_cls = "rsk-active" if cat["count"] > 0 else "rsk-clear"
sts_color = "#ef5350" if cat["count"] > 0 else "#333"
cat_html += f'''
<div class="rsk-card" style="flex:1;">
<div style="font-size:1.2rem;">{cat["icon"]}</div>
<div class="ind-lbl">{cat["label"]}</div>
<div class="rsk-cnt {cnt_cls}">{cat["count"]}</div>
<div style="color:{sts_color}; font-size:0.5rem; font-family:'IBM Plex Mono',monospace; letter-spacing:0.1em;">{cat["status"]}</div>
</div>'''
cat_html += '</div>'
st.markdown(cat_html, unsafe_allow_html=True)
high_docs = [d for d in risk_report["documents"] if d["severity"] == "HIGH"]
if high_docs:
st.markdown('<p class="lbl">High-Severity Signals</p>', unsafe_allow_html=True)
for doc in high_docs[:3]:
risks_html = " ".join(f'<span class="sev-{r["severity"]}">{r["icon"]} {r["label"]}</span>' for r in doc["risks"][:3])
st.markdown(f'''
<div class="src-card" style="border-left:3px solid #ef5350;">
<div class="src-hdr"><span>{doc["source"].upper()} · {doc["date"]}</span><span class="sev-HIGH">HIGH</span></div>
<div style="margin-top:0.3rem;">{risks_html}</div>
<div class="src-preview">{doc["preview"]}...</div>
</div>''', unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
st.markdown('<p class="lbl">Deal Scenario Assessment</p>', unsafe_allow_html=True)
scenario = st.text_area(
"sc", placeholder="e.g. Long 500k bbl WTI Q1 2027, Permian sourced, Houston → Rotterdam",
height=80, label_visibility="collapsed",
)
if st.button("Assess Risk", key="risk_btn") and scenario:
with st.spinner("Scanning..."):
answer, sources = oil.deal_risk_with_sources(scenario)
st.markdown(f'<div class="risk-out">{answer}</div>', unsafe_allow_html=True)
render_sources(sources)
# ── TAB 5: Eval ──────────────────────────────────────────────────────────────
with tab5:
st.markdown('<p class="lbl">System Evaluation</p>', unsafe_allow_html=True)
if st.button("Run Evaluation Suite", key="eval_btn"):
from risk_and_eval import RAGEvaluator
with st.spinner("Running 6-question eval suite..."):
ev = RAGEvaluator(oil).evaluate()
metrics = [
("Retrieval Precision", ev["retrieval_precision"]),
("Keyword Coverage", ev["keyword_coverage"]),
("Numeric Accuracy", ev["numeric_accuracy"]),
("Hallucination Resistance", ev["hallucination_resistance"]),
]
mcols = st.columns(4)
for col, (label, score) in zip(mcols, metrics):
with col:
cls = "ev-pass" if score >= 0.8 else "ev-warn" if score >= 0.5 else "ev-fail"
st.markdown(f'''
<div class="ev-card">
<div class="ev-lbl">{label}</div>
<div class="ev-val {cls}">{score:.0%}</div>
</div>''', unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
st.markdown('<p class="lbl">Question-Level Results</p>', unsafe_allow_html=True)
for r in ev["results"]:
icon = "✅" if r["overall_pass"] else "❌"
with st.expander(f'{icon} [{r["category"]}] {r["question"]}', expanded=False):
st.markdown(f'<div class="src-preview" style="max-height:none;">{r["answer"][:600]}</div>', unsafe_allow_html=True)
ccols = st.columns(4)
for col, (lbl, ok) in zip(ccols, [("Retrieval", r["retrieval_pass"]),
("Keywords", r["keyword_pass"]), ("Numeric", r["numeric_pass"]),
("Refusal", r["refusal_pass"])]):
c = "#4caf50" if ok else "#ef5350"
i = "✓" if ok else "✗"
with col:
st.markdown(f'<div style="text-align:center;color:{c};font-family:IBM Plex Mono,monospace;font-size:0.65rem;">{i} {lbl}</div>', unsafe_allow_html=True)
else:
st.markdown('''
<div class="out" style="border-left-color:#333;">
<strong>Methodology</strong> — 6 curated questions across 4 dimensions:
<strong>Retrieval Precision</strong> — correct source types retrieved
<strong>Keyword Coverage</strong> — expected domain terms in answer
<strong>Numeric Accuracy</strong> — numbers present when expected
<strong>Hallucination Resistance</strong> — refuses impossible queries
</div>''', unsafe_allow_html=True)
st.markdown('''
<hr style="margin-top:2rem;">
<p style="font-family:IBM Plex Mono,monospace; font-size:0.5rem; color:#1a1a1a; text-align:center; letter-spacing:0.1em;">
LLAMA 3.2 · FAISS · EIA · NEWSAPI · RESEARCH ONLY
</p>''', unsafe_allow_html=True)