Spaces:
Sleeping
Sleeping
File size: 34,054 Bytes
32dc112 |
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 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 |
"""
π MissionControlMCP - Interactive Demo
Try all 8 tools with real examples!
Run: python demo.py
"""
import sys
import os
import json
import base64
from pathlib import Path
# Setup paths
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(SCRIPT_DIR)
EXAMPLES_DIR = os.path.join(SCRIPT_DIR, "examples")
OUTPUT_DIR = os.path.join(SCRIPT_DIR, "demo_output")
# Create output directory
os.makedirs(OUTPUT_DIR, exist_ok=True)
# Import tools
from tools.pdf_reader import read_pdf
from tools.text_extractor import extract_text
from tools.web_fetcher import fetch_web_content
from tools.rag_search import search_documents
from tools.data_visualizer import visualize_data
from tools.file_converter import convert_file
from tools.email_intent_classifier import classify_email_intent
from tools.kpi_generator import generate_kpis
def print_header(title):
"""Print a nice header"""
print("\n" + "="*80)
print(f" {title}")
print("="*80)
def print_section(title):
"""Print a section header"""
print(f"\n{'β'*80}")
print(f"π {title}")
print(f"{'β'*80}")
def pause(message="Press Enter to continue..."):
"""Pause and wait for user input"""
input(f"\n{message}")
def save_chart(image_base64, filename):
"""Save base64 chart to file"""
filepath = os.path.join(OUTPUT_DIR, filename)
with open(filepath, "wb") as f:
f.write(base64.b64decode(image_base64))
print(f"πΎ Chart saved: {filepath}")
return filepath
# ============================================================================
# TOOL 1: PDF READER
# ============================================================================
def demo_pdf_reader():
"""Demo: PDF Reader - Extract text from PDFs"""
print_header("TOOL 1: PDF READER π")
print("\nπ What it does:")
print(" β’ Extracts all text from PDF files")
print(" β’ Gets metadata (author, title, pages)")
print(" β’ Perfect for reading reports, contracts, invoices")
print("\nπ‘ Real-world uses:")
print(" β’ Extract data from invoices")
print(" β’ Read research papers")
print(" β’ Process legal contracts")
print(" β’ Analyze business reports")
pause("\nReady to see it in action? Press Enter...")
# Check if user has their own PDF
print("\n" + "β"*80)
custom_pdf = input("Enter PDF file path (or press Enter to skip): ").strip()
if custom_pdf and os.path.exists(custom_pdf):
print(f"\nπ Reading your PDF: {custom_pdf}")
try:
result = read_pdf(custom_pdf)
print(f"\nβ
Successfully extracted:")
print(f" β’ Pages: {result['pages']}")
print(f" β’ Characters: {len(result['text']):,}")
print(f" β’ Author: {result['metadata'].get('author', 'N/A')}")
print(f"\nπ First 300 characters:")
print(result['text'][:300] + "...")
# Extract keywords from PDF
print("\nπ Extracting keywords from PDF...")
keywords = extract_text(result['text'], operation="keywords")
print(f"Keywords: {keywords['result']}")
except Exception as e:
print(f"β Error: {e}")
else:
print("\nπ Example: How it works")
print("```python")
print("result = read_pdf('document.pdf')")
print("print(f'Pages: {result[\"pages\"]}')")
print("print(result['text'][:500]) # First 500 chars")
print("```")
print("\n㪠Output:")
print(" Pages: 16")
print(" Text: College Of Engineering - System Analysis Project...")
pause()
# ============================================================================
# TOOL 2: TEXT EXTRACTOR
# ============================================================================
def demo_text_extractor():
"""Demo: Text Extractor - Process and analyze text"""
print_header("TOOL 2: TEXT EXTRACTOR π")
print("\nπ What it does:")
print(" β’ Extract keywords from any text")
print(" β’ Generate summaries (any length)")
print(" β’ Clean messy text")
print(" β’ Split text into chunks")
print("\nπ‘ Real-world uses:")
print(" β’ Summarize long documents")
print(" β’ Find main topics in articles")
print(" β’ Clean data before analysis")
print(" β’ Prepare text for processing")
pause("\nReady to try it? Press Enter...")
# Load sample report
print_section("Using sample business report")
sample_file = os.path.join(EXAMPLES_DIR, "sample_report.txt")
try:
with open(sample_file, "r", encoding="utf-8") as f:
text = f.read()
print(f"π Loaded text: {len(text)} characters")
print(f"\nPreview: {text[:200]}...")
pause("\nPress Enter to extract keywords...")
# Operation 1: Keywords
print_section("Operation 1: Extract Keywords")
keywords = extract_text(text, operation="keywords")
print(f"π Keywords: {keywords['result']}")
pause("\nPress Enter to generate summary...")
# Operation 2: Summarize
print_section("Operation 2: Generate Summary")
summary = extract_text(text, operation="summarize", max_length=300)
print(f"π Summary ({len(summary['result'])} chars):")
print(summary['result'])
pause("\nPress Enter to clean text...")
# Operation 3: Clean
print_section("Operation 3: Clean Text")
messy_text = " This has extra spaces\n\n\nand newlines "
cleaned = extract_text(messy_text, operation="clean")
print(f"Before: '{messy_text}'")
print(f"After: '{cleaned['result']}'")
# Operation 4: Chunk
print_section("Operation 4: Split into Chunks")
chunks = extract_text(text[:500], operation="chunk", max_length=100)
chunk_list = chunks['result'].split("\n\n---CHUNK---\n\n")
print(f"βοΈ Split into {len(chunk_list)} chunks (100 chars each)")
print(f"Chunk 1: {chunk_list[0][:80]}...")
# Try custom text
print("\n" + "β"*80)
custom_text = input("\nβοΈ Want to try your own text? Enter it (or press Enter to skip): ").strip()
if custom_text:
print("\nπ Keywords from your text:")
result = extract_text(custom_text, operation="keywords")
print(result['result'])
print("\nπ Summary of your text:")
result = extract_text(custom_text, operation="summarize", max_length=300)
if result['result']:
print(result['result'])
else:
# If summary is empty, show first 300 chars as fallback
print(custom_text[:300] + ("..." if len(custom_text) > 300 else ""))
except Exception as e:
print(f"β Error: {e}")
pause()
# ============================================================================
# TOOL 3: WEB FETCHER
# ============================================================================
def demo_web_fetcher():
"""Demo: Web Fetcher - Scrape web content"""
print_header("TOOL 3: WEB FETCHER π")
print("\nπ What it does:")
print(" β’ Fetches content from any website")
print(" β’ Extracts clean text (no HTML tags)")
print(" β’ Finds all links on the page")
print(" β’ Gets page title and metadata")
print("\nπ‘ Real-world uses:")
print(" β’ Monitor competitor websites")
print(" β’ Collect research data")
print(" β’ Track price changes")
print(" β’ Gather news articles")
pause("\nReady to fetch a website? Press Enter...")
# Allow retry loop
while True:
# Get URL from user
print("\n" + "β"*80)
url = input("Enter URL to fetch (or press Enter for example.com): ").strip()
if not url:
url = "https://example.com"
print(f"\nπ Fetching: {url}")
print("β³ Please wait...")
success = False
try:
result = fetch_web_content(url)
print(f"\nβ
Success!")
print(f" β’ Status: {result['status_code']}")
print(f" β’ Title: {result.get('title', 'N/A')}")
print(f" β’ Content length: {len(result['content']):,} characters")
print(f" β’ Links found: {len(result.get('links', []))}")
# Check if content is available
if result['status_code'] == 999:
print(f"\nβ οΈ Status 999 detected - Website is blocking automated requests")
print(" This is common for LinkedIn, Facebook, and other sites with bot protection")
print(" Try a different website!")
elif not result['content'].strip():
print(f"\nβ οΈ No content extracted - the page might be dynamic (JavaScript-based)")
else:
success = True
print(f"\nπ Content preview (first 500 chars):")
print(result['content'][:500] + "...")
if result.get('links'):
print(f"\nπ First 5 links:")
for link in result['links'][:5]:
print(f" β’ {link[:80]}") # Truncate long URLs
# Extract keywords from webpage
if len(result['content']) > 50:
pause("\nPress Enter to extract keywords from this page...")
keywords = extract_text(result['content'], operation="keywords")
print(f"\nπ Keywords from webpage:")
print(f" {keywords['result']}")
except Exception as e:
print(f"β Error fetching URL: {e}")
print("Tip: Make sure the URL is valid and accessible!")
# Ask if user wants to try another URL
print("\n" + "β"*80)
retry = input("Try another URL? (y/n): ").strip().lower()
if retry != 'y':
break
pause()
# ============================================================================
# TOOL 4: RAG SEARCH
# ============================================================================
def demo_rag_search():
"""Demo: RAG Search - Semantic document search"""
print_header("TOOL 4: RAG SEARCH π")
print("\nπ What it does:")
print(" β’ Semantic search (understands meaning, not just keywords)")
print(" β’ Finds relevant documents even with different words")
print(" β’ Uses AI embeddings (sentence transformers)")
print(" β’ Powered by FAISS vector database")
print("\nπ‘ Real-world uses:")
print(" β’ Search company knowledge base")
print(" β’ Find similar documents")
print(" β’ Answer questions from docs")
print(" β’ Build smart FAQ systems")
pause("\nReady to see semantic search in action? Press Enter...")
# Load sample documents
print_section("Loading sample documents")
docs_file = os.path.join(EXAMPLES_DIR, "sample_documents.txt")
try:
with open(docs_file, "r", encoding="utf-8") as f:
content = f.read()
documents = [doc.strip() for doc in content.split("##") if doc.strip()]
print(f"π Loaded {len(documents)} documents about:")
topics = ["AI & Machine Learning", "Climate Change", "Web Development",
"Digital Marketing", "Financial Technology"]
for i, topic in enumerate(topics, 1):
print(f" {i}. {topic}")
pause("\nPress Enter to search...")
# Example searches
queries = [
("What is machine learning?", "Testing: Does it find AI doc?"),
("How to reduce carbon emissions?", "Testing: Does it find climate doc?"),
("What are modern web frameworks?", "Testing: Does it find web dev doc?"),
]
for query, description in queries:
print_section(description)
print(f"π Query: '{query}'")
print("β³ Searching...")
result = search_documents(query, documents, top_k=2)
print(f"\nβ
Found {len(result['results'])} relevant results:")
for i, res in enumerate(result['results'], 1):
preview = res['document'][:120].replace('\n', ' ')
print(f"\n {i}. Relevance Score: {res['score']:.4f}")
print(f" {preview}...")
pause()
# Custom search
print("\n" + "β"*80)
custom_query = input("\nβοΈ Try your own search query (or press Enter to skip): ").strip()
if custom_query:
print(f"\nπ Searching for: '{custom_query}'")
result = search_documents(custom_query, documents, top_k=3)
print(f"\nπ Top {len(result['results'])} results:")
for i, res in enumerate(result['results'], 1):
preview = res['document'][:100].replace('\n', ' ')
print(f"\n {i}. Score: {res['score']:.4f}")
print(f" {preview}...")
except Exception as e:
print(f"β Error: {e}")
import traceback
traceback.print_exc()
pause()
# ============================================================================
# TOOL 5: DATA VISUALIZER
# ============================================================================
def demo_data_visualizer():
"""Demo: Data Visualizer - Create charts"""
print_header("TOOL 5: DATA VISUALIZER π")
print("\nπ What it does:")
print(" β’ Creates beautiful charts from data")
print(" β’ Supports: Bar, Line, Pie, Scatter plots")
print(" β’ Accepts CSV or JSON data")
print(" β’ Exports as PNG images")
print("\nπ‘ Real-world uses:")
print(" β’ Visualize sales trends")
print(" β’ Create financial reports")
print(" β’ Compare performance metrics")
print(" β’ Present data insights")
pause("\nReady to create charts? Press Enter...")
# Load sample data
print_section("Loading business data")
csv_file = os.path.join(EXAMPLES_DIR, "business_data.csv")
try:
with open(csv_file, "r") as f:
csv_data = f.read()
print("π Sample data (12 months):")
print(csv_data[:200] + "...")
pause("\nPress Enter to create LINE CHART (Revenue Trends)...")
# Chart 1: Line chart
print_section("Creating Chart 1: Revenue Line Chart")
result1 = visualize_data(
data=csv_data,
chart_type="line",
x_column="month",
y_column="revenue",
title="Monthly Revenue Trends 2024"
)
filepath1 = save_chart(result1['image_base64'], "revenue_trends.png")
print(f"β
Line chart created!")
print(f" Size: {len(result1['image_base64']):,} bytes (base64)")
print(f" Dimensions: {result1['dimensions']}")
pause("\nPress Enter to create BAR CHART (Monthly Costs)...")
# Chart 2: Bar chart
print_section("Creating Chart 2: Costs Bar Chart")
result2 = visualize_data(
data=csv_data,
chart_type="bar",
x_column="month",
y_column="costs",
title="Monthly Costs 2024"
)
filepath2 = save_chart(result2['image_base64'], "monthly_costs.png")
print(f"β
Bar chart created!")
pause("\nPress Enter to create PIE CHART (Customer Distribution)...")
# Chart 3: Pie chart
print_section("Creating Chart 3: Customers Pie Chart")
# Create sample pie data
pie_data = """category,value
Q1,650
Q2,600
Q3,550
Q4,500"""
result3 = visualize_data(
data=pie_data,
chart_type="pie",
x_column="category",
y_column="value",
title="Customers by Quarter"
)
filepath3 = save_chart(result3['image_base64'], "customer_pie.png")
print(f"β
Pie chart created!")
print(f"\nπ All charts saved in: {OUTPUT_DIR}")
print(f" β’ {os.path.basename(filepath1)}")
print(f" β’ {os.path.basename(filepath2)}")
print(f" β’ {os.path.basename(filepath3)}")
print("\nπ‘ You can open these PNG files to view the charts!")
except Exception as e:
print(f"β Error: {e}")
import traceback
traceback.print_exc()
pause()
# ============================================================================
# TOOL 6: FILE CONVERTER
# ============================================================================
def demo_file_converter():
"""Demo: File Converter - Convert between formats"""
print_header("TOOL 6: FILE CONVERTER π")
print("\nπ What it does:")
print(" β’ Convert PDF β TXT")
print(" β’ Convert TXT β CSV")
print(" β’ Batch file processing")
print(" β’ Preserves data integrity")
print("\nπ‘ Real-world uses:")
print(" β’ Extract text from PDFs")
print(" β’ Convert reports to CSV for analysis")
print(" β’ Prepare data for databases")
print(" β’ Archive documents in different formats")
print("\nπ§ Available conversions:")
print(" β’ pdf_to_txt - Extract text from PDF")
print(" β’ txt_to_pdf - Create PDF from text")
print(" β’ csv_to_txt - Convert CSV to plain text")
print(" β’ txt_to_csv - Structure text as CSV")
pause("\nReady to see file conversions? Press Enter...")
try:
# Demo 1: CSV to TXT
print_section("Demo 1: CSV β TXT Conversion")
csv_file = os.path.join(EXAMPLES_DIR, "business_data.csv")
txt_output = os.path.join(OUTPUT_DIR, "business_data.txt")
print(f"π Converting: business_data.csv β business_data.txt")
print("β³ Processing...")
result1 = convert_file(
input_path=csv_file,
output_path=txt_output,
conversion_type="csv_to_txt"
)
if result1['success']:
print(f"β
Conversion successful!")
print(f" Output: {result1['output_file']}")
# Show preview
with open(txt_output, 'r', encoding='utf-8') as f:
preview = f.read()[:300]
print(f"\nπ Preview of converted file:")
print(preview + "...")
pause("\nPress Enter for next conversion...")
# Demo 2: TXT to CSV
print_section("Demo 2: TXT β CSV Conversion")
txt_input = os.path.join(EXAMPLES_DIR, "sample_report.txt")
csv_output = os.path.join(OUTPUT_DIR, "sample_report.csv")
print(f"π Converting: sample_report.txt β sample_report.csv")
print("β³ Processing...")
result2 = convert_file(
input_path=txt_input,
output_path=csv_output,
conversion_type="txt_to_csv"
)
if result2['success']:
print(f"β
Conversion successful!")
print(f" Output: {result2['output_file']}")
# Show preview
with open(csv_output, 'r', encoding='utf-8') as f:
lines = f.readlines()[:5]
print(f"\nπ First 5 lines of CSV:")
for line in lines:
print(f" {line.strip()}")
print(f"\nοΏ½ Converted files saved in: {OUTPUT_DIR}")
print(f" β’ business_data.txt")
print(f" β’ sample_report.csv")
# Offer custom conversion
print("\n" + "β"*80)
print("\nπ§ Want to convert your own file?")
print("Supported conversions: pdf_to_txt, txt_to_pdf, csv_to_txt, txt_to_csv")
custom_input = input("\nEnter input file path (or press Enter to skip): ").strip()
if custom_input and os.path.exists(custom_input):
custom_output = input("Enter output file path: ").strip()
conversion_type = input("Enter conversion type (e.g., pdf_to_txt): ").strip()
if custom_output and conversion_type:
print(f"\nπ Converting {os.path.basename(custom_input)}...")
try:
result = convert_file(custom_input, custom_output, conversion_type)
if result['success']:
print(f"β
Success! File saved: {result['output_file']}")
except Exception as e:
print(f"β Conversion failed: {e}")
except Exception as e:
print(f"β Error: {e}")
import traceback
traceback.print_exc()
pause()
# ============================================================================
# TOOL 7: EMAIL INTENT CLASSIFIER
# ============================================================================
def demo_email_classifier():
"""Demo: Email Intent Classifier - Understand email purpose"""
print_header("TOOL 7: EMAIL INTENT CLASSIFIER π§")
print("\nπ What it does:")
print(" β’ Automatically classifies email intent")
print(" β’ Detects 10 different types")
print(" β’ Gives confidence scores")
print(" β’ Finds secondary intents too")
print("\n㪠Detects these intents:")
intents = [
"complaint", "inquiry", "request", "feedback", "order",
"meeting", "urgent", "application", "sales", "other"
]
for i, intent in enumerate(intents, 1):
print(f" {i:2d}. {intent.title()}")
print("\nπ‘ Real-world uses:")
print(" β’ Auto-route customer emails")
print(" β’ Prioritize urgent messages")
print(" β’ Organize inbox automatically")
print(" β’ Track complaint patterns")
pause("\nReady to classify emails? Press Enter...")
# Test with sample emails
email_files = [
("sample_email_complaint.txt", "Customer Complaint"),
("sample_email_inquiry.txt", "Sales Inquiry"),
("sample_email_urgent.txt", "Urgent Issue"),
]
for filename, label in email_files:
print_section(f"Email: {label}")
filepath = os.path.join(EXAMPLES_DIR, filename)
try:
with open(filepath, "r", encoding="utf-8") as f:
email_text = f.read()
print(f"π§ Email content:")
print(email_text[:200] + "...\n")
result = classify_email_intent(email_text)
print(f"π― Classification Results:")
print(f" Primary Intent: {result['intent'].upper()}")
print(f" Confidence: {result['confidence']:.2%}")
if result['secondary_intents']:
print(f"\n Secondary Intents:")
for intent in result['secondary_intents'][:3]:
print(f" β’ {intent['intent']}: {intent['confidence']:.2%}")
print(f"\n㪠{result['explanation']}")
pause()
except Exception as e:
print(f"β Error: {e}")
# Custom email
print("\n" + "β"*80)
print("\nβοΈ Want to try your own email?")
custom_email = input("Paste email text (or press Enter to skip): ").strip()
if custom_email:
print("\nπ Analyzing your email...")
result = classify_email_intent(custom_email)
print(f"\nπ― Intent: {result['intent'].upper()}")
print(f" Confidence: {result['confidence']:.2%}")
if result['secondary_intents']:
print(f" Also detected: {result['secondary_intents'][0]['intent']}")
pause()
# ============================================================================
# TOOL 8: KPI GENERATOR
# ============================================================================
def demo_kpi_generator():
"""Demo: KPI Generator - Calculate business metrics"""
print_header("TOOL 8: KPI GENERATOR π")
print("\nπ What it does:")
print(" β’ Calculates business KPIs automatically")
print(" β’ Analyzes 5 metric categories")
print(" β’ Identifies trends and insights")
print(" β’ Generates executive summaries")
print("\nπ Metric categories:")
print(" 1. Revenue - Total revenue, profit, margins")
print(" 2. Growth - Growth rates, trends over time")
print(" 3. Efficiency - Revenue per employee/customer")
print(" 4. Customer - Customer acquisition, retention")
print(" 5. Operational - Operational efficiency metrics")
print("\nπ‘ Real-world uses:")
print(" β’ Monthly performance reports")
print(" β’ Executive dashboards")
print(" β’ Investor presentations")
print(" β’ Business health monitoring")
pause("\nReady to generate KPIs? Press Enter...")
# Sample business data
print_section("Sample Business Data")
business_data = {
"revenue": 5500000,
"costs": 3400000,
"customers": 2700,
"current_revenue": 5500000,
"previous_revenue": 5400000,
"current_customers": 2700,
"previous_customers": 2650,
"employees": 50,
"marketing_spend": 500000,
"sales": 5500000,
"cogs": 2000000
}
print("π Input data:")
for key, value in business_data.items():
if 'revenue' in key or 'cost' in key or 'spend' in key or 'sales' in key or 'cogs' in key:
print(f" β’ {key}: ${value:,}")
else:
print(f" β’ {key}: {value:,}")
pause("\nPress Enter to calculate KPIs...")
try:
# Generate KPIs
print_section("Calculating KPIs")
print("β³ Analyzing data...")
result = generate_kpis(
json.dumps(business_data),
metrics=["revenue", "growth", "efficiency"]
)
print(f"\nβ
Generated {len(result['kpis'])} KPIs:")
print("\nπ Key Metrics:")
# Display KPIs nicely
kpi_items = list(result['kpis'].items())
for i, (name, value) in enumerate(kpi_items[:10], 1): # Show top 10
# Format based on metric type
if 'percent' in name or 'rate' in name or 'margin' in name:
formatted = f"{value:.1f}%"
elif 'revenue' in name or 'profit' in name or 'cost' in name:
formatted = f"${value:,.0f}"
else:
formatted = f"{value:,.2f}"
# Clean name
display_name = name.replace('_', ' ').title()
print(f" {i:2d}. {display_name}: {formatted}")
if len(kpi_items) > 10:
print(f" ... and {len(kpi_items) - 10} more")
pause("\nPress Enter to see executive summary...")
# Summary
print_section("Executive Summary")
print(result['summary'])
# Trends
if result.get('trends'):
print("\nπ Key Trends Identified:")
for i, trend in enumerate(result['trends'], 1):
print(f" {i}. {trend}")
# Try custom data
print("\n" + "β"*80)
print("\nβοΈ Want to calculate KPIs for your own data?")
print("Enter JSON data (or press Enter to skip):")
print("Example: {\"revenue\": 1000000, \"costs\": 600000, \"customers\": 500}")
custom_data = input("\nYour data: ").strip()
if custom_data:
try:
# Validate JSON
json.loads(custom_data)
result = generate_kpis(custom_data, metrics=["revenue"])
print(f"\nβ
Your KPIs:")
for name, value in list(result['kpis'].items())[:5]:
print(f" β’ {name}: {value}")
except json.JSONDecodeError:
print("β Invalid JSON format!")
except Exception as e:
print(f"β Error: {e}")
except Exception as e:
print(f"β Error: {e}")
import traceback
traceback.print_exc()
pause()
# ============================================================================
# MAIN MENU
# ============================================================================
def show_menu():
"""Display main menu"""
print("\n" + "β" + "β"*78 + "β")
print("β" + " "*20 + "π MissionControlMCP Demo" + " "*33 + "β")
print("β" + " "*25 + "Try All 8 Tools!" + " "*36 + "β")
print("β" + "β"*78 + "β")
print("\nπ MENU - Choose a tool to try:")
print("\n [1] π PDF Reader - Extract text from PDFs")
print(" [2] π Text Extractor - Keywords, summaries, cleaning")
print(" [3] π Web Fetcher - Scrape website content")
print(" [4] π RAG Search - Semantic document search")
print(" [5] π Data Visualizer - Create beautiful charts")
print(" [6] π File Converter - Convert file formats")
print(" [7] π§ Email Classifier - Detect email intent")
print(" [8] π KPI Generator - Business metrics & insights")
print("\n [9] π― Run ALL Tools - Full demo (recommended!)")
print(" [0] πͺ Exit")
print("\n" + "β"*80)
def run_all_tools():
"""Run all tool demos in sequence"""
print_header("π― RUNNING ALL TOOLS - COMPLETE DEMO")
print("\nThis will walk you through all 8 tools with examples.")
print("You can pause, try your own data, and explore each tool.")
pause("\nReady to start? Press Enter...")
tools = [
demo_pdf_reader,
demo_text_extractor,
demo_web_fetcher,
demo_rag_search,
demo_data_visualizer,
demo_file_converter,
demo_email_classifier,
demo_kpi_generator
]
for i, tool_func in enumerate(tools, 1):
print(f"\n\n{'='*80}")
print(f" TOOL {i} OF {len(tools)}")
print(f"{'='*80}")
tool_func()
print_header("π DEMO COMPLETE!")
print("\nβ
You've explored all 8 MissionControlMCP tools!")
print(f"\nπ Generated files saved in: {OUTPUT_DIR}")
print("\nπ‘ Next steps:")
print(" β’ Try the tools with your own data")
print(" β’ Integrate with Claude Desktop")
print(" β’ Build custom workflows")
print(" β’ Check out the documentation (README.md)")
print("\nπ Happy automating!")
def main():
"""Main program loop"""
print("\n" + "β" + "β"*78 + "β")
print("β" + " "*15 + "Welcome to MissionControlMCP Demo!" + " "*29 + "β")
print("β" + "β"*78 + "β")
print("\nπ This interactive demo lets you:")
print(" β
Try all 8 enterprise automation tools")
print(" β
See real examples with sample data")
print(" β
Test with your own data")
print(" β
Understand what each tool does")
pause("\nPress Enter to continue...")
while True:
show_menu()
choice = input("\nπ Enter your choice (0-9): ").strip()
if choice == "1":
demo_pdf_reader()
elif choice == "2":
demo_text_extractor()
elif choice == "3":
demo_web_fetcher()
elif choice == "4":
demo_rag_search()
elif choice == "5":
demo_data_visualizer()
elif choice == "6":
demo_file_converter()
elif choice == "7":
demo_email_classifier()
elif choice == "8":
demo_kpi_generator()
elif choice == "9":
run_all_tools()
elif choice == "0":
print("\nπ Thanks for trying MissionControlMCP!")
print("π Check out the docs for more: README.md")
break
else:
print("\nβ Invalid choice! Please enter 0-9")
# Ask if user wants to continue
if choice != "9": # Don't ask after running all tools
print("\n" + "β"*80)
continue_choice = input("Return to menu? (y/n): ").strip().lower()
if continue_choice != 'y':
print("\nπ Thanks for trying MissionControlMCP!")
break
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\nπ Demo interrupted. See you next time!")
except Exception as e:
print(f"\n\nβ Unexpected error: {e}")
import traceback
traceback.print_exc()
|