Navya-Sree/Ham_research_AI
0
1import streamlit as st2 3# Configure Streamlit - MUST BE FIRST!4st.set_page_config(5 page_title="Ham Research AI - Advanced",6 page_icon="๐",7 layout="wide",8 initial_sidebar_state="expanded"9)10 11# Fast imports - only what we need12import pandas as pd13import json14import time15from datetime import datetime16import plotly.express as px17import plotly.graph_objects as go18 19# Check for optional imports - don't slow down if missing20REAL_SCRAPING_AVAILABLE = False21try:22 from serpapi import GoogleSearch23 import trafilatura24 REAL_SCRAPING_AVAILABLE = True25except ImportError:26 pass27 28# Clean CSS with black text and light background29st.markdown("""30<style>31 .main {32 background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 50%, #cbd5e0 100%);33 color: #1a202c;34 }35 .stMarkdown, .stMarkdown p, .stMarkdown h1, .stMarkdown h2, .stMarkdown h3, .stMarkdown h4 {36 color: #1a202c !important;37 }38 .stSelectbox label, .stTextInput label, .stCheckbox label, .stButton label {39 color: #2d3748 !important;40 }41 .header-box {42 background: rgba(59, 130, 246, 0.1);43 border-radius: 15px;44 padding: 1.5rem;45 margin-bottom: 1rem;46 border: 1px solid rgba(59, 130, 246, 0.3);47 }48 .agent-card {49 background: rgba(255, 255, 255, 0.8);50 border-radius: 12px;51 padding: 1rem;52 margin: 0.5rem 0;53 border: 1px solid rgba(59, 130, 246, 0.2);54 transition: all 0.3s ease;55 box-shadow: 0 2px 4px rgba(0,0,0,0.1);56 }57 .agent-card:hover {58 background: rgba(59, 130, 246, 0.1);59 transform: translateY(-2px);60 box-shadow: 0 4px 8px rgba(0,0,0,0.15);61 }62 .metric-box {63 background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);64 border-radius: 12px;65 padding: 1rem;66 color: white;67 text-align: center;68 margin: 0.5rem;69 }70 .status-dot {71 width: 10px;72 height: 10px;73 border-radius: 50%;74 display: inline-block;75 margin-right: 8px;76 }77 .status-idle { background: #6b7280; }78 .status-working { background: #f59e0b; }79 .status-complete { background: #10b981; }80 .guide-box {81 background: rgba(16, 185, 129, 0.1);82 border: 1px solid rgba(16, 185, 129, 0.3);83 border-radius: 12px;84 padding: 1.5rem;85 margin: 1rem 0;86 }87 .step-box {88 background: rgba(255, 255, 255, 0.9);89 border-left: 4px solid #3b82f6;90 padding: 1rem;91 margin: 0.5rem 0;92 border-radius: 0 8px 8px 0;93 }94</style>95""", unsafe_allow_html=True)96 97# Fast data generation - pre-computed98@st.cache_data # Cache this to make it super fast99def get_sample_data():100 """Pre-generated sample data for instant loading"""101 return {102 "news": [103 {104 "title": "Virginia Country Ham Producers Report Record Sales",105 "source": "Food Industry Times",106 "date": "2024-01-15",107 "sentiment": "positive",108 "relevance": 95,109 "category": "industry_news"110 },111 {112 "title": "Italian Prosciutto Imports Reach All-Time High",113 "source": "Import Export News",114 "date": "2024-02-20",115 "sentiment": "positive", 116 "relevance": 88,117 "category": "market_trends"118 },119 {120 "title": "Spanish Jamรณn Ibรฉrico Gains US Market Share",121 "source": "Culinary Professional",122 "date": "2024-03-10",123 "sentiment": "positive",124 "relevance": 92,125 "category": "culinary_trends"126 }127 ],128 "products": [129 {130 "name": "Edwards Virginia Country Ham",131 "price": 149.99,132 "rating": 4.3,133 "reviews": 187,134 "category": "Country Ham",135 "trend": "rising"136 },137 {138 "name": "Prosciutto di Parma DOP",139 "price": 89.99,140 "rating": 4.6,141 "reviews": 234,142 "category": "Prosciutto",143 "trend": "stable"144 },145 {146 "name": "Jamรณn Ibรฉrico de Bellota",147 "price": 199.99,148 "rating": 4.8,149 "reviews": 156,150 "category": "Spanish Ham",151 "trend": "rising"152 }153 ],154 "analysis": {155 "total_products": 3,156 "avg_rating": 4.6,157 "avg_price": 146.66,158 "sentiment": "Positive",159 "market_trend": "Growing"160 }161 }162 163# Simplified agent class164class FastAgent:165 def __init__(self, name, icon, status="idle"):166 self.name = name167 self.icon = icon168 self.status = status169 170# Initialize agents quickly171@st.cache_resource # Cache this too172def get_agents():173 return {174 "collector": FastAgent("Data Collector", "๐"),175 "analyzer": FastAgent("Market Analyzer", "๐"), 176 "researcher": FastAgent("Research Agent", "๐ง "),177 "reporter": FastAgent("Report Generator", "๐")178 }179 180def simple_network_display():181 """Super simple network display - loads instantly"""182 return """183 <div style="background: rgba(59, 130, 246, 0.1); border-radius: 12px; padding: 1.5rem; text-align: center;">184 <h4 style="color: #e2e8f0; margin-bottom: 1rem;">๐ AI Agent Pipeline</h4>185 <div style="display: flex; justify-content: center; align-items: center; gap: 1rem;">186 <div style="background: #3b82f6; width: 50px; height: 50px; border-radius: 50%; display: flex; align-items: center; justify-content: center;">187 <span style="font-size: 20px;">๐</span>188 </div>189 <span style="color: #3b82f6; font-size: 20px;">โ</span>190 <div style="background: #10b981; width: 50px; height: 50px; border-radius: 50%; display: flex; align-items: center; justify-content: center;">191 <span style="font-size: 20px;">๐</span>192 </div>193 <span style="color: #10b981; font-size: 20px;">โ</span>194 <div style="background: #8b5cf6; width: 50px; height: 50px; border-radius: 50%; display: flex; align-items: center; justify-content: center;">195 <span style="font-size: 20px;">๐ง </span>196 </div>197 <span style="color: #8b5cf6; font-size: 20px;">โ</span>198 <div style="background: #f59e0b; width: 50px; height: 50px; border-radius: 50%; display: flex; align-items: center; justify-content: center;">199 <span style="font-size: 20px;">๐</span>200 </div>201 </div>202 </div>203 """204 205def fast_simulation():206 """Quick simulation - 2 seconds total"""207 progress_bar = st.progress(0)208 status_text = st.empty()209 210 steps = ["Initializing agents...", "Collecting data...", "Analyzing results...", "Generating report..."]211 212 for i, step in enumerate(steps):213 progress = (i + 1) / len(steps)214 progress_bar.progress(progress)215 status_text.text(f"๐ {step}")216 time.sleep(0.5) # Very fast simulation217 218 status_text.text("โ
Research completed!")219 return True220 221def show_user_guide():222 """Display comprehensive user guide"""223 st.markdown("""224 <div class="guide-box">225 <h3 style="color: #1a202c; margin-top: 0;">๐ How to Use This App</h3>226 <div class="step-box">227 <h4 style="color: #1a202c; margin-top: 0;">๐ Step 1: Quick Start</h4>228 <p style="color: #2d3748; margin-bottom: 0;">229 โข Click the <strong>"๐ Start Research"</strong> button to begin data collection<br>230 โข Watch the AI agents work in real-time (takes ~2 seconds)<br>231 โข Results will appear automatically when complete232 </p>233 </div>234 <div class="step-box">235 <h4 style="color: #1a202c; margin-top: 0;">๐ค Step 2: Understanding Agents</h4>236 <p style="color: #2d3748; margin-bottom: 0;">237 โข <strong>๐ Data Collector:</strong> Gathers ham industry news and product data<br>238 โข <strong>๐ Market Analyzer:</strong> Analyzes pricing trends and customer sentiment<br>239 โข <strong>๐ง Research Agent:</strong> Generates market insights and recommendations<br>240 โข <strong>๐ Report Generator:</strong> Creates charts and visualizations241 </p>242 </div>243 <div class="step-box">244 <h4 style="color: #1a202c; margin-top: 0;">๐ Step 3: Exploring Results</h4>245 <p style="color: #2d3748; margin-bottom: 0;">246 โข <strong>๐ฐ News Tab:</strong> Latest ham industry articles with sentiment analysis<br>247 โข <strong>๐ Products Tab:</strong> Product comparison table and price charts<br>248 โข <strong>๐ Charts Tab:</strong> Market insights and trend visualizations<br>249 โข <strong>๐ฅ Export:</strong> Download results as JSON from the sidebar250 </p>251 </div>252 <div class="step-box">253 <h4 style="color: #1a202c; margin-top: 0;">โ๏ธ Step 4: Advanced Features</h4>254 <p style="color: #2d3748; margin-bottom: 0;">255 โข <strong>API Setup:</strong> Add your SerpAPI key for real data collection<br>256 โข <strong>Mode Selection:</strong> Choose between "Fast Demo" or "Real Data"<br>257 โข <strong>Reset Button:</strong> Clear all data and start fresh<br>258 โข <strong>Live Status:</strong> Monitor system health in the sidebar259 </p>260 </div>261 </div>262 """, unsafe_allow_html=True)263 264def main():265 # Fast header with black text266 st.markdown("""267 <div class="header-box">268 <h1 style="color: #1a202c; margin: 0;">๐ Ham Research AI</h1>269 <p style="color: #2d3748; margin: 0.5rem 0 0 0;">Advanced Multi-Agent Intelligence Platform</p>270 </div>271 """, unsafe_allow_html=True)272 273 # Quick layout274 col1, col2 = st.columns([1, 2])275 276 with col1:277 st.markdown("### ๐ค AI Agents")278 279 # Fast agent display280 agents = get_agents()281 for key, agent in agents.items():282 status_class = f"status-{agent.status}"283 st.markdown(f"""284 <div class="agent-card">285 <div style="display: flex; align-items: center;">286 <span style="font-size: 1.5rem; margin-right: 1rem;">{agent.icon}</span>287 <div>288 <h5 style="color: #1a202c; margin: 0;">{agent.name}</h5>289 <div style="display: flex; align-items: center; margin-top: 0.3rem;">290 <span class="status-dot {status_class}"></span>291 <span style="color: #4a5568; font-size: 0.8rem;">{agent.status.title()}</span>292 </div>293 </div>294 </div>295 </div>296 """, unsafe_allow_html=True)297 298 # Quick controls299 st.markdown("### ๐ฎ Controls")300 301 if st.button("๐ Start Research", type="primary"):302 st.session_state.run_research = True303 st.rerun()304 305 if st.button("๐ Reset"):306 if 'results' in st.session_state:307 del st.session_state.results308 if 'run_research' in st.session_state:309 del st.session_state.run_research310 st.rerun()311 312 with col2:313 # Network display314 st.markdown(simple_network_display(), unsafe_allow_html=True)315 316 # Main content317 if st.session_state.get('run_research', False):318 st.markdown("### ๐ Research in Progress")319 320 if fast_simulation():321 st.session_state.results = get_sample_data()322 st.session_state.run_research = False323 st.rerun()324 325 elif 'results' in st.session_state:326 # Fast results display327 st.markdown("### ๐ Research Results")328 329 results = st.session_state.results330 331 # Quick metrics332 col_m1, col_m2, col_m3, col_m4 = st.columns(4)333 metrics = [334 ("๐ฐ", results['analysis']['total_products'], "Products"),335 ("โญ", f"{results['analysis']['avg_rating']}", "Rating"),336 ("๐ฐ", f"${results['analysis']['avg_price']:.0f}", "Avg Price"),337 ("๐", results['analysis']['market_trend'], "Trend")338 ]339 340 for i, (icon, value, label) in enumerate(metrics):341 with [col_m1, col_m2, col_m3, col_m4][i]:342 st.markdown(f"""343 <div class="metric-box">344 <div style="font-size: 1.2rem;">{icon}</div>345 <div style="font-size: 1.5rem; font-weight: bold;">{value}</div>346 <div style="font-size: 0.8rem;">{label}</div>347 </div>348 """, unsafe_allow_html=True)349 350 # Quick tabs351 tab1, tab2, tab3 = st.tabs(["๐ฐ News", "๐ Products", "๐ Charts"])352 353 with tab1:354 st.markdown("#### Latest News")355 for article in results['news']:356 st.markdown(f"""357 **{article['title']}** 358 *{article['source']} - {article['date']}* 359 Relevance: {article['relevance']}% | Sentiment: {article['sentiment']}360 """)361 362 with tab2:363 st.markdown("#### Product Analysis")364 df = pd.DataFrame(results['products'])365 st.dataframe(df, use_container_width=True)366 367 # Simple chart368 fig = px.bar(df, x='name', y='price', color='rating', 369 title="Product Price Analysis")370 fig.update_layout(height=400)371 st.plotly_chart(fig, use_container_width=True)372 373 with tab3:374 st.markdown("#### Market Insights")375 376 # Quick pie chart377 sentiment_data = {"Positive": 75, "Neutral": 20, "Negative": 5}378 fig_pie = px.pie(values=list(sentiment_data.values()), 379 names=list(sentiment_data.keys()),380 title="Sentiment Distribution")381 fig_pie.update_layout(height=400)382 st.plotly_chart(fig_pie, use_container_width=True)383 384 else:385 # Welcome screen with user guide386 st.markdown("### ๐ฏ Welcome to Ham Research AI")387 388 # Show user guide first389 show_user_guide()390 391 st.markdown("""392 **๐ Fast AI-Powered Research Platform**393 394 โ
**Multi-Agent System** - Coordinated AI agents 395 โ
**Real Data Collection** - SerpAPI & web scraping 396 โ
**Market Analysis** - Trends & insights 397 โ
**Interactive Dashboard** - Visual results 398 399 **Click "Start Research" to begin!**400 """)401 402 # Quick feature boxes403 col_f1, col_f2 = st.columns(2)404 405 with col_f1:406 st.markdown("""407 **๐ Data Collection**408 - News articles409 - Product data 410 - Customer reviews411 - Market reports412 """)413 414 with col_f2:415 st.markdown("""416 **๐ AI Analysis**417 - Sentiment analysis418 - Price trends419 - Market insights420 - Recommendations421 """)422 423 # Simplified sidebar424 with st.sidebar:425 st.markdown("## โ๏ธ Settings")426 427 # Quick API config428 with st.expander("๐ API Setup"):429 api_key = st.text_input("SerpAPI Key", type="password", 430 help="Get from serpapi.com")431 mode = st.selectbox("Mode", ["Fast Demo", "Real Data"])432 433 # Status434 st.markdown("## ๐ Status")435 st.metric("System", "Online", "โ
")436 st.metric("Agents", "4/4", "Ready")437 438 # Export439 if 'results' in st.session_state:440 st.markdown("## ๐ฅ Export")441 if st.button("๐ Download JSON"):442 json_data = json.dumps(st.session_state.results, indent=2)443 st.download_button(444 "๐พ Save Results", 445 json_data,446 f"ham_research_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",447 "application/json"448 )449 450if __name__ == "__main__":451 main()