Spaces:
Sleeping
Sleeping
| """ | |
| π MissionControlMCP - Gradio Web Interface | |
| Beautiful GUI demo for all 8 tools! | |
| Run: python demo_gui.py | |
| Then share the public URL on LinkedIn! | |
| """ | |
| import gradio as gr | |
| import sys | |
| import os | |
| import json | |
| import base64 | |
| from io import BytesIO | |
| from PIL import Image | |
| # Setup paths | |
| SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.append(SCRIPT_DIR) | |
| EXAMPLES_DIR = os.path.join(SCRIPT_DIR, "examples") | |
| # 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 | |
| # ============================================================================ | |
| # TOOL FUNCTIONS | |
| # ============================================================================ | |
| def tool_pdf_reader(pdf_file): | |
| """PDF Reader tool""" | |
| try: | |
| if pdf_file is None: | |
| return "β Please upload a PDF file!", None | |
| result = read_pdf(pdf_file.name) | |
| output = f"""β **PDF Analysis Complete!** | |
| π **Metadata:** | |
| - Pages: {result['pages']} | |
| - Characters: {len(result['text']):,} | |
| - Author: {result['metadata'].get('author', 'N/A')} | |
| - Title: {result['metadata'].get('title', 'N/A')} | |
| π **Extracted Text (first 1000 chars):** | |
| {result['text'][:1000]}... | |
| """ | |
| # Extract keywords | |
| keywords = extract_text(result['text'], operation="keywords") | |
| output += f"\n\nπ **Keywords:** {keywords['result']}" | |
| return output, None | |
| except Exception as e: | |
| return f"β Error: {str(e)}", None | |
| def tool_text_extractor(text, operation, max_length): | |
| """Text Extractor tool""" | |
| try: | |
| if not text.strip(): | |
| return "β Please enter some text!" | |
| result = extract_text(text, operation=operation, max_length=max_length) | |
| output = f"""β **Text Processing Complete!** | |
| π **Operation:** {operation.upper()} | |
| π **Word Count:** {result['word_count']} | |
| π **Result:** | |
| {result['result']} | |
| """ | |
| return output | |
| except Exception as e: | |
| return f"β Error: {str(e)}" | |
| def tool_web_fetcher(url): | |
| """Web Fetcher tool""" | |
| try: | |
| if not url.strip(): | |
| return "β Please enter a URL!" | |
| result = fetch_web_content(url) | |
| if result['status_code'] == 999: | |
| return f"""β οΈ **Status 999 - Bot Detection** | |
| The website is blocking automated requests. | |
| This is common for LinkedIn, Facebook, etc. | |
| Try a different website!""" | |
| output = f"""β **Website Fetched Successfully!** | |
| π **URL:** {url} | |
| π **Status:** {result['status_code']} | |
| π **Title:** {result.get('title', 'N/A')} | |
| π **Content Length:** {len(result['content']):,} characters | |
| π **Links Found:** {len(result.get('links', []))} | |
| π **Content Preview (first 1000 chars):** | |
| {result['content'][:1000]}... | |
| """ | |
| # Extract keywords | |
| if len(result['content']) > 50: | |
| keywords = extract_text(result['content'], operation="keywords") | |
| output += f"\n\nπ **Keywords:** {keywords['result']}" | |
| return output | |
| except Exception as e: | |
| return f"β Error: {str(e)}" | |
| def tool_rag_search(query): | |
| """RAG Search tool""" | |
| try: | |
| if not query.strip(): | |
| return "β Please enter a search query!" | |
| # Load sample documents | |
| docs_file = os.path.join(EXAMPLES_DIR, "sample_documents.txt") | |
| with open(docs_file, "r", encoding="utf-8") as f: | |
| content = f.read() | |
| documents = [doc.strip() for doc in content.split("##") if doc.strip()] | |
| result = search_documents(query, documents, top_k=3) | |
| output = f"""β **Search Complete!** | |
| π **Query:** "{query}" | |
| π **Documents Searched:** {len(documents)} | |
| π **Results Found:** {len(result['results'])} | |
| π― **Top Results:** | |
| """ | |
| for i, res in enumerate(result['results'], 1): | |
| preview = res['document'][:200].replace('\n', ' ') | |
| output += f""" | |
| **Result {i}** (Score: {res['score']:.4f}) | |
| {preview}... | |
| """ | |
| return output | |
| except Exception as e: | |
| return f"β Error: {str(e)}" | |
| def tool_data_visualizer(csv_data, chart_type, x_col, y_col, title): | |
| """Data Visualizer tool""" | |
| try: | |
| if not csv_data.strip(): | |
| return "β Please enter CSV data!", None | |
| result = visualize_data( | |
| data=csv_data, | |
| chart_type=chart_type, | |
| x_column=x_col, | |
| y_column=y_col, | |
| title=title | |
| ) | |
| # Convert base64 to image | |
| img_data = base64.b64decode(result['image_base64']) | |
| image = Image.open(BytesIO(img_data)) | |
| output = f"""β **Chart Created!** | |
| π **Chart Type:** {chart_type.upper()} | |
| π **Dimensions:** {result['dimensions']} | |
| π **Title:** {title} | |
| """ | |
| return output, image | |
| except Exception as e: | |
| return f"β Error: {str(e)}", None | |
| def tool_email_classifier(email_text): | |
| """Email Intent Classifier tool""" | |
| try: | |
| if not email_text.strip(): | |
| return "β Please enter email text!" | |
| result = classify_email_intent(email_text) | |
| output = f"""β **Email Classified!** | |
| π― **Primary Intent:** {result['intent'].upper()} | |
| π **Confidence:** {result['confidence']:.2%} | |
| π¬ **Explanation:** | |
| {result['explanation']} | |
| """ | |
| if result['secondary_intents']: | |
| output += "\n\nπ **Secondary Intents:**\n" | |
| for intent in result['secondary_intents'][:3]: | |
| output += f"- {intent['intent']}: {intent['confidence']:.2%}\n" | |
| return output | |
| except Exception as e: | |
| return f"β Error: {str(e)}" | |
| def tool_kpi_generator(business_json, metrics): | |
| """KPI Generator tool""" | |
| try: | |
| if not business_json.strip(): | |
| return "β Please enter business data!" | |
| # Validate JSON | |
| json.loads(business_json) | |
| result = generate_kpis(business_json, metrics=metrics) | |
| output = f"""β **KPIs Generated!** | |
| π **Total KPIs Calculated:** {len(result['kpis'])} | |
| π **Key Metrics:** | |
| """ | |
| # Display top 15 KPIs | |
| for i, (name, value) in enumerate(list(result['kpis'].items())[:15], 1): | |
| # 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}" | |
| display_name = name.replace('_', ' ').title() | |
| output += f"{i}. **{display_name}:** {formatted}\n" | |
| output += f"\n\nπ **Executive Summary:**\n{result['summary']}" | |
| if result.get('trends'): | |
| output += "\n\nπ **Key Trends:**\n" | |
| for trend in result['trends'][:5]: | |
| output += f"- {trend}\n" | |
| return output | |
| except json.JSONDecodeError: | |
| return "β Invalid JSON format! Please check your data." | |
| except Exception as e: | |
| return f"β Error: {str(e)}" | |
| # ============================================================================ | |
| # LOAD SAMPLE DATA | |
| # ============================================================================ | |
| def load_sample_csv(): | |
| csv_file = os.path.join(EXAMPLES_DIR, "business_data.csv") | |
| with open(csv_file, "r") as f: | |
| return f.read() | |
| def load_sample_email(): | |
| email_file = os.path.join(EXAMPLES_DIR, "sample_email_complaint.txt") | |
| with open(email_file, "r", encoding="utf-8") as f: | |
| return f.read() | |
| def load_sample_json(): | |
| return """{ | |
| "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 | |
| }""" | |
| # ============================================================================ | |
| # GRADIO INTERFACE | |
| # ============================================================================ | |
| # Custom CSS | |
| custom_css = """ | |
| .gradio-container { | |
| font-family: 'Arial', sans-serif; | |
| } | |
| .tab-label { | |
| font-size: 16px !important; | |
| } | |
| """ | |
| # Create Gradio interface | |
| with gr.Blocks(theme=gr.themes.Soft(), css=custom_css, title="MissionControlMCP Demo") as demo: | |
| gr.Markdown(""" | |
| # π MissionControlMCP - Enterprise Automation Tools | |
| **Try all 8 powerful tools in your browser!** No installation needed. | |
| π Built for the HuggingFace Gradio Hackathon | π Claude MCP Integration | |
| """) | |
| with gr.Tabs(): | |
| # ====== TAB 1: PDF READER ====== | |
| with gr.Tab("π PDF Reader"): | |
| gr.Markdown("### Extract text and metadata from PDF documents") | |
| with gr.Row(): | |
| with gr.Column(): | |
| pdf_input = gr.File(label="Upload PDF", file_types=[".pdf"]) | |
| pdf_btn = gr.Button("π Extract Text", variant="primary") | |
| with gr.Column(): | |
| pdf_output = gr.Textbox(label="Results", lines=15) | |
| pdf_img = gr.Image(label="Preview", visible=False) | |
| pdf_btn.click(tool_pdf_reader, inputs=[pdf_input], outputs=[pdf_output, pdf_img]) | |
| gr.Examples([["Use the file upload above to try with your own PDF!"]], inputs=[]) | |
| # ====== TAB 2: TEXT EXTRACTOR ====== | |
| with gr.Tab("π Text Extractor"): | |
| gr.Markdown("### Extract keywords, generate summaries, clean text") | |
| with gr.Row(): | |
| with gr.Column(): | |
| text_input = gr.Textbox( | |
| label="Enter Text", | |
| lines=8, | |
| placeholder="Paste your text here..." | |
| ) | |
| text_operation = gr.Radio( | |
| ["keywords", "summarize", "clean", "chunk"], | |
| label="Operation", | |
| value="keywords" | |
| ) | |
| text_length = gr.Slider(100, 1000, 300, label="Max Length (for summarize/chunk)") | |
| text_btn = gr.Button("β¨ Process Text", variant="primary") | |
| with gr.Column(): | |
| text_output = gr.Textbox(label="Results", lines=15) | |
| text_btn.click( | |
| tool_text_extractor, | |
| inputs=[text_input, text_operation, text_length], | |
| outputs=[text_output] | |
| ) | |
| gr.Examples([ | |
| ["Artificial Intelligence is transforming businesses worldwide. Companies are leveraging AI for automation, decision-making, and customer service. Machine learning models can now process vast amounts of data and provide actionable insights.", "keywords", 300], | |
| ["Climate change is one of the most pressing challenges of our time. Rising temperatures, extreme weather events, and environmental degradation require urgent action.", "summarize", 300] | |
| ], inputs=[text_input, text_operation, text_length]) | |
| # ====== TAB 3: WEB FETCHER ====== | |
| with gr.Tab("π Web Fetcher"): | |
| gr.Markdown("### Scrape and analyze web content") | |
| with gr.Row(): | |
| with gr.Column(): | |
| web_input = gr.Textbox( | |
| label="Website URL", | |
| placeholder="https://example.com", | |
| value="https://example.com" | |
| ) | |
| web_btn = gr.Button("π Fetch Website", variant="primary") | |
| with gr.Column(): | |
| web_output = gr.Textbox(label="Results", lines=15) | |
| web_btn.click(tool_web_fetcher, inputs=[web_input], outputs=[web_output]) | |
| gr.Examples([ | |
| ["https://example.com"], | |
| ["https://python.org"], | |
| ["https://github.com"] | |
| ], inputs=[web_input]) | |
| # ====== TAB 4: RAG SEARCH ====== | |
| with gr.Tab("π RAG Search"): | |
| gr.Markdown("### Semantic document search with AI embeddings") | |
| with gr.Row(): | |
| with gr.Column(): | |
| rag_input = gr.Textbox( | |
| label="Search Query", | |
| placeholder="What are you looking for?", | |
| value="What is machine learning?" | |
| ) | |
| rag_btn = gr.Button("π Search Documents", variant="primary") | |
| with gr.Column(): | |
| rag_output = gr.Textbox(label="Search Results", lines=15) | |
| rag_btn.click(tool_rag_search, inputs=[rag_input], outputs=[rag_output]) | |
| gr.Examples([ | |
| ["What is machine learning?"], | |
| ["How to reduce carbon emissions?"], | |
| ["What are modern web frameworks?"], | |
| ["Digital marketing strategies"] | |
| ], inputs=[rag_input]) | |
| # ====== TAB 5: DATA VISUALIZER ====== | |
| with gr.Tab("π Data Visualizer"): | |
| gr.Markdown("### Create beautiful charts from CSV data") | |
| with gr.Row(): | |
| with gr.Column(): | |
| viz_csv = gr.Textbox( | |
| label="CSV Data", | |
| lines=8, | |
| value=load_sample_csv(), | |
| placeholder="month,revenue,costs\nJan,100000,60000" | |
| ) | |
| viz_chart = gr.Radio( | |
| ["line", "bar", "pie", "scatter"], | |
| label="Chart Type", | |
| value="line" | |
| ) | |
| viz_x = gr.Textbox(label="X Column", value="month") | |
| viz_y = gr.Textbox(label="Y Column", value="revenue") | |
| viz_title = gr.Textbox(label="Chart Title", value="Monthly Revenue") | |
| viz_btn = gr.Button("π Create Chart", variant="primary") | |
| with gr.Column(): | |
| viz_output = gr.Textbox(label="Status", lines=5) | |
| viz_img = gr.Image(label="Chart") | |
| viz_btn.click( | |
| tool_data_visualizer, | |
| inputs=[viz_csv, viz_chart, viz_x, viz_y, viz_title], | |
| outputs=[viz_output, viz_img] | |
| ) | |
| # ====== TAB 6: EMAIL CLASSIFIER ====== | |
| with gr.Tab("π§ Email Classifier"): | |
| gr.Markdown("### Detect email intent with AI") | |
| with gr.Row(): | |
| with gr.Column(): | |
| email_input = gr.Textbox( | |
| label="Email Text", | |
| lines=10, | |
| value=load_sample_email(), | |
| placeholder="Paste email content here..." | |
| ) | |
| email_btn = gr.Button("π― Classify Email", variant="primary") | |
| with gr.Column(): | |
| email_output = gr.Textbox(label="Classification Results", lines=15) | |
| email_btn.click(tool_email_classifier, inputs=[email_input], outputs=[email_output]) | |
| gr.Examples([ | |
| ["I am writing to complain about the poor service I received at your store yesterday."], | |
| ["Could you please send me more information about your pricing plans?"], | |
| ["URGENT: The server is down and customers cannot access the website!"] | |
| ], inputs=[email_input]) | |
| # ====== TAB 7: KPI GENERATOR ====== | |
| with gr.Tab("π KPI Generator"): | |
| gr.Markdown("### Calculate business metrics and KPIs") | |
| with gr.Row(): | |
| with gr.Column(): | |
| kpi_json = gr.Textbox( | |
| label="Business Data (JSON)", | |
| lines=12, | |
| value=load_sample_json(), | |
| placeholder='{"revenue": 1000000, "costs": 600000}' | |
| ) | |
| kpi_metrics = gr.CheckboxGroup( | |
| ["revenue", "growth", "efficiency", "customer", "operational"], | |
| label="Metrics to Calculate", | |
| value=["revenue", "growth", "efficiency"] | |
| ) | |
| kpi_btn = gr.Button("π Generate KPIs", variant="primary") | |
| with gr.Column(): | |
| kpi_output = gr.Textbox(label="KPI Report", lines=20) | |
| kpi_btn.click( | |
| tool_kpi_generator, | |
| inputs=[kpi_json, kpi_metrics], | |
| outputs=[kpi_output] | |
| ) | |
| # Footer | |
| gr.Markdown(""" | |
| --- | |
| ### π― About MissionControlMCP | |
| 8 enterprise-grade automation tools integrated with Claude Desktop via Model Context Protocol (MCP). | |
| - **PDF Reader** - Extract text from documents | |
| - **Text Extractor** - Keywords, summaries, cleaning | |
| - **Web Fetcher** - Scrape websites | |
| - **RAG Search** - Semantic document search | |
| - **Data Visualizer** - Create charts | |
| - **File Converter** - Format conversions | |
| - **Email Classifier** - Intent detection | |
| - **KPI Generator** - Business analytics | |
| π **GitHub:** [AlBaraa-1/CleanEye-Hackathon](https://github.com/AlBaraa-1/CleanEye-Hackathon) | |
| π Built for HuggingFace Gradio x BuildWithMCP Hackathon | |
| """) | |
| # ============================================================================ | |
| # LAUNCH | |
| # ============================================================================ | |
| if __name__ == "__main__": | |
| print("\n" + "="*80) | |
| print("π Launching MissionControlMCP Web Interface...") | |
| print("="*80) | |
| # Launch with public sharing enabled | |
| demo.launch( | |
| share=True, # Creates public URL! | |
| server_name="0.0.0.0", | |
| server_port=7860, | |
| show_error=True | |
| ) | |