import gradio as gr import plotly.graph_objects as go import requests from bs4 import BeautifulSoup from duckduckgo_search import DDGS from transformers import pipeline from datetime import datetime, timedelta import logging import random # Set up logging for debugging and operational insight logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') # Initialize transformer models for summarization try: summarizer = pipeline("summarization", model="facebook/bart-large-cnn") report_summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6") logging.info("Transformer models loaded successfully.") except Exception as e: logging.error("Error loading transformer pipelines: %s", e) summarizer = None report_summarizer = None ########################################## # BUSINESS ANALYSIS & ROI FUNCTIONS # ########################################## def create_performance_comparison(): """ Generates a bar chart comparing current setup with upgraded GPU. """ categories = [ 'AI Model Loading', 'VS Code Extensions', 'Local Offline AI Assistants', 'Image Processing', 'Multi-tasking', 'Large Dataset Analysis' ] current_values = [20, 15, 10, 18, 25, 12] potential_values = [100, 100, 100, 100, 100, 100] fig = go.Figure(data=[ go.Bar(name='Current Setup (2GB VRAM)', x=categories, y=current_values, marker_color='#2D3748'), go.Bar(name='Potential (Upgraded GPU)', x=categories, y=potential_values, marker_color='#4A5568') ]) fig.update_layout( title={'text': 'Performance Comparison Analysis', 'font': {'size': 24}}, barmode='group', yaxis_title='Relative Performance (%)', plot_bgcolor='white', font={'family': 'Arial', 'size': 14}, legend={'orientation': 'h', 'x': 0.2, 'y': 1.1} ) return fig def create_roi_projection(): """ Creates a 24-month ROI projection chart. """ months = list(range(1, 25)) base_revenue = 1000 current_growth_rate = 0.1 upgraded_growth_rate = 0.25 current_revenue = [base_revenue * (1 + current_growth_rate) ** i for i in range(len(months))] projected_revenue = [base_revenue * (1 + upgraded_growth_rate) ** i for i in range(len(months))] total_investment = 3000 additional_revenue = sum(projected_revenue) - sum(current_revenue) roi_percentage = (additional_revenue / total_investment) * 100 fig = go.Figure() fig.add_trace(go.Scatter( x=months, y=current_revenue, name='Current Revenue', line={'color': '#2D3748', 'width': 3} )) fig.add_trace(go.Scatter( x=months, y=projected_revenue, name='Projected Revenue with GPU Upgrade', line={'color': '#4A5568', 'width': 3} )) fig.update_layout( title={'text': f'24-Month Revenue Projection (ROI: {roi_percentage:.1f}%)', 'font': {'size': 24}}, xaxis_title='Month', yaxis_title='Revenue (USD)', plot_bgcolor='white', font={'family': 'Arial', 'size': 14}, legend={'orientation': 'h', 'x': 0.3, 'y': 1.1} ) return fig def calculate_loan_details(loan_amount, interest_rate=5.0): """ Calculates detailed monthly loan repayment schedule. """ try: amount = float(loan_amount) annual_rate = float(interest_rate) / 100 monthly_rate = annual_rate / 12 grace_period = 3 repayment_period = 12 monthly_payment = amount * (monthly_rate * (1 + monthly_rate) ** repayment_period) / ((1 + monthly_rate) ** repayment_period - 1) schedule = "📊 **Detailed Loan Repayment Schedule**\n\n" schedule += f"**💰 Loan Amount:** ${amount:,.2f}\n" schedule += f"**⏳ Grace Period:** {grace_period} months\n" schedule += f"**📈 Annual Interest Rate:** {interest_rate}%\n" schedule += f"**💵 Monthly Payment (starting month {grace_period + 1}):** ${monthly_payment:,.2f}\n\n" remaining_balance = amount total_interest = 0 current_date = datetime.now() schedule += "**Monthly Breakdown:**\n" for month in range(1, repayment_period + grace_period + 1): date = current_date + timedelta(days=30 * month) if month <= grace_period: schedule += f"- {date.strftime('%B %Y')}: Grace Period (No Payment)\n" else: interest = remaining_balance * monthly_rate principal = monthly_payment - interest remaining_balance -= principal total_interest += interest schedule += f"- {date.strftime('%B %Y')}: ${monthly_payment:,.2f} (Principal: ${principal:,.2f}, Interest: ${interest:,.2f})\n" schedule += f"\n**📊 Total Interest Paid:** ${total_interest:,.2f}" return schedule except ValueError: return "⚠️ Please enter a valid loan amount" ########################################## # ROBUST WEB SCRAPING AGENT # ########################################## def robust_web_scrape_agent(url): """ Extracts content from URL using multiple user-agents and fallback methods. """ user_agents = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/115.0.0.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Version/15.1 Safari/605.1.15", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/114.0.0.0 Safari/537.36", ] headers = {'User-Agent': random.choice(user_agents)} try: response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return f"Error: Received status code {response.status_code}" soup = BeautifulSoup(response.text, "html.parser") for tag in soup(["script", "style", "noscript"]): tag.decompose() text = soup.get_text(separator="\n").strip() if not text or len(text) < 200: try: from readability import Document doc = Document(response.text) extracted_html = doc.summary() fallback_soup = BeautifulSoup(extracted_html, "html.parser") text = fallback_soup.get_text(separator="\n").strip() except ImportError: logging.error("Readability module not available.") except Exception as fallback_error: logging.error("Fallback extraction failed: %s", fallback_error) return text if text and len(text) >= 200 else "No substantial content found." except Exception as e: return f"Error during scraping: {e}" def research_agent(query): """ Performs web search using DuckDuckGo. """ try: with DDGS() as ddgs: results = ddgs.text(query, max_results=5) if results: return "\n\n".join([f"**{result.get('title', 'No Title')}**:\n{result.get('href', 'No URL')}" for result in results]) return "No results found." except Exception as e: return f"Error during research: {e}" def report_agent(data): """ Generates summary report using transformer model. """ try: if not report_summarizer: return "Report summarization is not available." if len(data.split()) < 30: return "Input text is too short for summarization." summary = report_summarizer(data, max_length=130, min_length=30, do_sample=False) return summary[0]['summary_text'] except Exception as e: return f"Error during report generation: {e}" ########################################## # EARNINGS PLOT FUNCTION # ########################################## def create_earnings_plot(): """ Plots earnings history. """ dates = ["2024-12-10", "2024-12-17", "2024-12-24", "2024-12-31", "2025-01-07", "2025-01-14", "2025-01-21", "2025-01-28", "2025-02-04", "2025-02-11"] earnings = [156.02, 73.10, 97.07, 116.11, 79.05, 86.62, 54.57, 86.36, 61.50, 79.18] fig = go.Figure(data=go.Scatter( x=dates, y=earnings, mode='lines+markers', line=dict(color='#4A5568', width=3) )) fig.update_layout( title={'text': 'Personal Earnings History', 'font': {'size': 24}}, xaxis_title='Date', yaxis_title='Earnings (USD)', plot_bgcolor='white', font={'family': 'Arial', 'size': 14} ) return fig ########################################## # GRADIO INTERFACE # ########################################## with gr.Blocks(theme=gr.themes.Default( primary_hue="slate", secondary_hue="slate", neutral_hue="slate", font=["Arial", "sans-serif"] )) as demo: # Ko-fi banner at top gr.HTML("""
Scaling AI Innovation through Strategic Investment