import streamlit as st # Configure Streamlit - MUST BE FIRST! st.set_page_config( page_title="Ham Research AI - Advanced", page_icon="๐Ÿ–", layout="wide", initial_sidebar_state="expanded" ) # Fast imports - only what we need import pandas as pd import json import time from datetime import datetime import plotly.express as px import plotly.graph_objects as go # Check for optional imports - don't slow down if missing REAL_SCRAPING_AVAILABLE = False try: from serpapi import GoogleSearch import trafilatura REAL_SCRAPING_AVAILABLE = True except ImportError: pass # Clean CSS with black text and light background st.markdown(""" """, unsafe_allow_html=True) # Fast data generation - pre-computed @st.cache_data # Cache this to make it super fast def get_sample_data(): """Pre-generated sample data for instant loading""" return { "news": [ { "title": "Virginia Country Ham Producers Report Record Sales", "source": "Food Industry Times", "date": "2024-01-15", "sentiment": "positive", "relevance": 95, "category": "industry_news" }, { "title": "Italian Prosciutto Imports Reach All-Time High", "source": "Import Export News", "date": "2024-02-20", "sentiment": "positive", "relevance": 88, "category": "market_trends" }, { "title": "Spanish Jamรณn Ibรฉrico Gains US Market Share", "source": "Culinary Professional", "date": "2024-03-10", "sentiment": "positive", "relevance": 92, "category": "culinary_trends" } ], "products": [ { "name": "Edwards Virginia Country Ham", "price": 149.99, "rating": 4.3, "reviews": 187, "category": "Country Ham", "trend": "rising" }, { "name": "Prosciutto di Parma DOP", "price": 89.99, "rating": 4.6, "reviews": 234, "category": "Prosciutto", "trend": "stable" }, { "name": "Jamรณn Ibรฉrico de Bellota", "price": 199.99, "rating": 4.8, "reviews": 156, "category": "Spanish Ham", "trend": "rising" } ], "analysis": { "total_products": 3, "avg_rating": 4.6, "avg_price": 146.66, "sentiment": "Positive", "market_trend": "Growing" } } # Simplified agent class class FastAgent: def __init__(self, name, icon, status="idle"): self.name = name self.icon = icon self.status = status # Initialize agents quickly @st.cache_resource # Cache this too def get_agents(): return { "collector": FastAgent("Data Collector", "๐Ÿ”"), "analyzer": FastAgent("Market Analyzer", "๐Ÿ“Š"), "researcher": FastAgent("Research Agent", "๐Ÿง "), "reporter": FastAgent("Report Generator", "๐Ÿ“„") } def simple_network_display(): """Super simple network display - loads instantly""" return """

๐ŸŒ AI Agent Pipeline

๐Ÿ”
โ†’
๐Ÿ“Š
โ†’
๐Ÿง 
โ†’
๐Ÿ“„
""" def fast_simulation(): """Quick simulation - 2 seconds total""" progress_bar = st.progress(0) status_text = st.empty() steps = ["Initializing agents...", "Collecting data...", "Analyzing results...", "Generating report..."] for i, step in enumerate(steps): progress = (i + 1) / len(steps) progress_bar.progress(progress) status_text.text(f"๐Ÿš€ {step}") time.sleep(0.5) # Very fast simulation status_text.text("โœ… Research completed!") return True def show_user_guide(): """Display comprehensive user guide""" st.markdown("""

๐Ÿ“š How to Use This App

๐Ÿš€ Step 1: Quick Start

โ€ข Click the "๐Ÿš€ Start Research" button to begin data collection
โ€ข Watch the AI agents work in real-time (takes ~2 seconds)
โ€ข Results will appear automatically when complete

๐Ÿค– Step 2: Understanding Agents

โ€ข ๐Ÿ” Data Collector: Gathers ham industry news and product data
โ€ข ๐Ÿ“Š Market Analyzer: Analyzes pricing trends and customer sentiment
โ€ข ๐Ÿง  Research Agent: Generates market insights and recommendations
โ€ข ๐Ÿ“„ Report Generator: Creates charts and visualizations

๐Ÿ“Š Step 3: Exploring Results

โ€ข ๐Ÿ“ฐ News Tab: Latest ham industry articles with sentiment analysis
โ€ข ๐Ÿ›’ Products Tab: Product comparison table and price charts
โ€ข ๐Ÿ“Š Charts Tab: Market insights and trend visualizations
โ€ข ๐Ÿ“ฅ Export: Download results as JSON from the sidebar

โš™๏ธ Step 4: Advanced Features

โ€ข API Setup: Add your SerpAPI key for real data collection
โ€ข Mode Selection: Choose between "Fast Demo" or "Real Data"
โ€ข Reset Button: Clear all data and start fresh
โ€ข Live Status: Monitor system health in the sidebar

""", unsafe_allow_html=True) def main(): # Fast header with black text st.markdown("""

๐Ÿ– Ham Research AI

Advanced Multi-Agent Intelligence Platform

""", unsafe_allow_html=True) # Quick layout col1, col2 = st.columns([1, 2]) with col1: st.markdown("### ๐Ÿค– AI Agents") # Fast agent display agents = get_agents() for key, agent in agents.items(): status_class = f"status-{agent.status}" st.markdown(f"""
{agent.icon}
{agent.name}
{agent.status.title()}
""", unsafe_allow_html=True) # Quick controls st.markdown("### ๐ŸŽฎ Controls") if st.button("๐Ÿš€ Start Research", type="primary"): st.session_state.run_research = True st.rerun() if st.button("๐Ÿ”„ Reset"): if 'results' in st.session_state: del st.session_state.results if 'run_research' in st.session_state: del st.session_state.run_research st.rerun() with col2: # Network display st.markdown(simple_network_display(), unsafe_allow_html=True) # Main content if st.session_state.get('run_research', False): st.markdown("### ๐Ÿ”„ Research in Progress") if fast_simulation(): st.session_state.results = get_sample_data() st.session_state.run_research = False st.rerun() elif 'results' in st.session_state: # Fast results display st.markdown("### ๐Ÿ“Š Research Results") results = st.session_state.results # Quick metrics col_m1, col_m2, col_m3, col_m4 = st.columns(4) metrics = [ ("๐Ÿ“ฐ", results['analysis']['total_products'], "Products"), ("โญ", f"{results['analysis']['avg_rating']}", "Rating"), ("๐Ÿ’ฐ", f"${results['analysis']['avg_price']:.0f}", "Avg Price"), ("๐Ÿ“ˆ", results['analysis']['market_trend'], "Trend") ] for i, (icon, value, label) in enumerate(metrics): with [col_m1, col_m2, col_m3, col_m4][i]: st.markdown(f"""
{icon}
{value}
{label}
""", unsafe_allow_html=True) # Quick tabs tab1, tab2, tab3 = st.tabs(["๐Ÿ“ฐ News", "๐Ÿ›’ Products", "๐Ÿ“Š Charts"]) with tab1: st.markdown("#### Latest News") for article in results['news']: st.markdown(f""" **{article['title']}** *{article['source']} - {article['date']}* Relevance: {article['relevance']}% | Sentiment: {article['sentiment']} """) with tab2: st.markdown("#### Product Analysis") df = pd.DataFrame(results['products']) st.dataframe(df, use_container_width=True) # Simple chart fig = px.bar(df, x='name', y='price', color='rating', title="Product Price Analysis") fig.update_layout(height=400) st.plotly_chart(fig, use_container_width=True) with tab3: st.markdown("#### Market Insights") # Quick pie chart sentiment_data = {"Positive": 75, "Neutral": 20, "Negative": 5} fig_pie = px.pie(values=list(sentiment_data.values()), names=list(sentiment_data.keys()), title="Sentiment Distribution") fig_pie.update_layout(height=400) st.plotly_chart(fig_pie, use_container_width=True) else: # Welcome screen with user guide st.markdown("### ๐ŸŽฏ Welcome to Ham Research AI") # Show user guide first show_user_guide() st.markdown(""" **๐Ÿš€ Fast AI-Powered Research Platform** โœ… **Multi-Agent System** - Coordinated AI agents โœ… **Real Data Collection** - SerpAPI & web scraping โœ… **Market Analysis** - Trends & insights โœ… **Interactive Dashboard** - Visual results **Click "Start Research" to begin!** """) # Quick feature boxes col_f1, col_f2 = st.columns(2) with col_f1: st.markdown(""" **๐Ÿ” Data Collection** - News articles - Product data - Customer reviews - Market reports """) with col_f2: st.markdown(""" **๐Ÿ“Š AI Analysis** - Sentiment analysis - Price trends - Market insights - Recommendations """) # Simplified sidebar with st.sidebar: st.markdown("## โš™๏ธ Settings") # Quick API config with st.expander("๐Ÿ”‘ API Setup"): api_key = st.text_input("SerpAPI Key", type="password", help="Get from serpapi.com") mode = st.selectbox("Mode", ["Fast Demo", "Real Data"]) # Status st.markdown("## ๐Ÿ“Š Status") st.metric("System", "Online", "โœ…") st.metric("Agents", "4/4", "Ready") # Export if 'results' in st.session_state: st.markdown("## ๐Ÿ“ฅ Export") if st.button("๐Ÿ“„ Download JSON"): json_data = json.dumps(st.session_state.results, indent=2) st.download_button( "๐Ÿ’พ Save Results", json_data, f"ham_research_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json", "application/json" ) if __name__ == "__main__": main()