File size: 18,806 Bytes
6ded552
761d965
 
6ded552
 
761d965
4ad5bf3
8ac0059
 
4ad5bf3
5739c3c
 
761d965
 
6ded552
 
324d629
6ded552
 
 
 
 
 
 
 
 
 
 
 
 
015d23b
 
 
6ded552
 
 
 
 
015d23b
 
6ded552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d664d4
6ded552
5d664d4
6ded552
5d664d4
6ded552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d664d4
 
6ded552
5d664d4
 
 
6ded552
5d664d4
6ded552
5d664d4
6ded552
 
 
5d664d4
6ded552
 
 
 
 
 
 
5d664d4
 
6ded552
5d664d4
 
 
6ded552
 
5d664d4
 
6ded552
5d664d4
 
6ded552
 
5d664d4
6ded552
 
283d889
6ded552
 
 
283d889
6ded552
5d664d4
6ded552
324d629
6ded552
 
5d664d4
6ded552
 
5d664d4
6ded552
5d664d4
324d629
6ded552
5d664d4
6ded552
5d664d4
324d629
5d664d4
6ded552
 
 
 
 
 
5d664d4
 
 
 
 
 
324d629
6ded552
5d664d4
6ded552
 
5d664d4
6ded552
5d664d4
 
6ded552
5d664d4
 
6ded552
5d664d4
 
6ded552
 
 
 
5d664d4
6ded552
 
 
5021b10
6ded552
5021b10
6ded552
324d629
6ded552
761d965
6ded552
8ac0059
324d629
6ded552
 
 
 
 
 
8ac0059
6ded552
8ac0059
324d629
6ded552
 
 
 
283d889
6ded552
 
324d629
 
8ac0059
761d965
324d629
6ded552
5021b10
324d629
 
6ded552
 
 
 
 
 
5021b10
324d629
6ded552
 
 
 
 
 
 
 
 
 
 
324d629
 
6ded552
324d629
 
6ded552
324d629
 
6ded552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5021b10
324d629
8ac0059
6ded552
 
 
324d629
 
6ded552
 
5021b10
8ac0059
 
6ded552
 
 
 
 
 
 
 
 
761d965
4ad5bf3
6ded552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

#!/usr/bin/env python
"""
PowerPoint MCP Server with Gradio interface and Streamable HTTP transport
Integrated with existing tool structure from ppt_mcp_server.py
"""
import os
import json
import tempfile
import time
import uuid
import logging
import gradio as gr
from threading import Thread
from typing import Dict, Any, Optional
from mcp.server.fastmcp import FastMCP
import asyncio
# Import all your existing tools registration functions
from tools import (
    register_presentation_tools,
    register_content_tools,
    register_structural_tools,
    register_professional_tools,
    register_template_tools,
    register_hyperlink_tools,
    register_chart_tools,
    register_connector_tools,
    register_master_tools,
    register_transition_tools
)
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialize the FastMCP server for streamable HTTP
mcp_app = FastMCP(
    name="ppt-mcp-server"
)
# Global state to store presentations in memory (from original)
presentations = {}
current_presentation_id = None
# Template configuration (from original)
def get_template_search_directories():
    """
    Get list of directories to search for templates.
    Uses environment variable PPT_TEMPLATE_PATH if set, otherwise uses default directories.
    """
    template_env_path = os.environ.get('PPT_TEMPLATE_PATH')
    
    if template_env_path:
        import platform
        separator = ';' if platform.system() == "Windows" else ':'
        env_dirs = [path.strip() for path in template_env_path.split(separator) if path.strip()]
        
        valid_env_dirs = []
        for dir_path in env_dirs:
            expanded_path = os.path.expanduser(dir_path)
            if os.path.exists(expanded_path) and os.path.isdir(expanded_path):
                valid_env_dirs.append(expanded_path)
        
        if valid_env_dirs:
            return valid_env_dirs + ['.', './templates', './assets', './resources']
        else:
            print(f"Warning: PPT_TEMPLATE_PATH directories not found: {template_env_path}")
    
    return ['.', './templates', './assets', './resources']
# Helper Functions (from original)
def get_current_presentation():
    """Get the current presentation object or raise an error if none is loaded."""
    if current_presentation_id is None or current_presentation_id not in presentations:
        raise ValueError("No presentation is currently loaded. Please create or open a presentation first.")
    return presentations[current_presentation_id]
def get_current_presentation_id():
    """Get the current presentation ID."""
    return current_presentation_id
def set_current_presentation_id(pres_id):
    """Set the current presentation ID."""
    global current_presentation_id
    current_presentation_id = pres_id
def validate_parameters(params):
    """Validate parameters against constraints."""
    for param_name, (value, constraints) in params.items():
        for constraint_func, error_msg in constraints:
            if not constraint_func(value):
                return False, f"Parameter '{param_name}': {error_msg}"
    return True, None
def is_positive(value):
    """Check if a value is positive."""
    return value > 0
def is_non_negative(value):
    """Check if a value is non-negative."""
    return value >= 0
def is_in_range(min_val, max_val):
    """Create a function that checks if a value is in a range."""
    return lambda x: min_val <= x <= max_val
def is_in_list(valid_list):
    """Create a function that checks if a value is in a list."""
    return lambda x: x in valid_list
def is_valid_rgb(color_list):
    """Check if a color list is a valid RGB tuple."""
    if not isinstance(color_list, list) or len(color_list) != 3:
        return False
    return all(isinstance(c, int) and 0 <= c <= 255 for c in color_list)
def add_shape_direct(slide, shape_type: str, left: float, top: float, width: float, height: float) -> Any:
    """Add an auto shape to a slide using direct integer values."""
    from pptx.util import Inches
    
    shape_type_map = {
        'rectangle': 1,
        'rounded_rectangle': 2, 
        'oval': 9,
        'diamond': 4,
        'triangle': 5,
        'right_triangle': 6,
        'pentagon': 56,
        'hexagon': 10,
        'heptagon': 11,
        'octagon': 12,
        'star': 12,
        'arrow': 13,
        'cloud': 35,
        'heart': 21,
        'lightning_bolt': 22,
        'sun': 23,
        'moon': 24,
        'smiley_face': 17,
        'no_symbol': 19,
        'flowchart_process': 112,
        'flowchart_decision': 114,
        'flowchart_data': 115,
        'flowchart_document': 119
    }
    
    shape_type_lower = str(shape_type).lower()
    if shape_type_lower not in shape_type_map:
        available_shapes = ', '.join(sorted(shape_type_map.keys()))
        raise ValueError(f"Unsupported shape type: '{shape_type}'. Available shape types: {available_shapes}")
    
    shape_value = shape_type_map[shape_type_lower]
    
    try:
        shape = slide.shapes.add_shape(
            shape_value, Inches(left), Inches(top), Inches(width), Inches(height)
        )
        return shape
    except Exception as e:
        raise ValueError(f"Failed to create '{shape_type}' shape using direct value {shape_value}: {str(e)}")
# Custom presentation management wrapper (from original)
class PresentationManager:
    """Wrapper to handle presentation state updates."""
    
    def __init__(self, presentations_dict):
        self.presentations = presentations_dict
    
    def store_presentation(self, pres, pres_id):
        """Store a presentation and set it as current."""
        self.presentations[pres_id] = pres
        set_current_presentation_id(pres_id)
        return pres_id
# Create presentation manager wrapper
presentation_manager = PresentationManager(presentations)
# Register all tool modules (from original)
register_presentation_tools(
    mcp_app, 
    presentations, 
    get_current_presentation_id, 
    get_template_search_directories
)
register_content_tools(
    mcp_app,
    presentations,
    get_current_presentation_id,
    validate_parameters,
    is_positive,
    is_non_negative,
    is_in_range,
    is_valid_rgb
)
register_structural_tools(
    mcp_app,
    presentations,
    get_current_presentation_id,
    validate_parameters,
    is_positive,
    is_non_negative,
    is_in_range,
    is_valid_rgb,
    add_shape_direct
)
register_professional_tools(
    mcp_app,
    presentations,
    get_current_presentation_id
)
register_template_tools(
    mcp_app,
    presentations,
    get_current_presentation_id
)
register_hyperlink_tools(
    mcp_app,
    presentations,
    get_current_presentation_id,
    validate_parameters,
    is_positive,
    is_non_negative,
    is_in_range,
    is_valid_rgb
)
register_chart_tools(
    mcp_app,
    presentations,
    get_current_presentation_id,
    validate_parameters,
    is_positive,
    is_non_negative,
    is_in_range,
    is_valid_rgb
)
register_connector_tools(
    mcp_app,
    presentations,
    get_current_presentation_id,
    validate_parameters,
    is_positive,
    is_non_negative,
    is_in_range,
    is_valid_rgb
)
register_master_tools(
    mcp_app,
    presentations,
    get_current_presentation_id,
    validate_parameters,
    is_positive,
    is_non_negative,
    is_in_range,
    is_valid_rgb
)
register_transition_tools(
    mcp_app,
    presentations,
    get_current_presentation_id,
    validate_parameters,
    is_positive,
    is_non_negative,
    is_in_range,
    is_valid_rgb
)
# Additional Utility Tools (from original)
@mcp_app.tool()
def list_presentations() -> Dict:
    """List all loaded presentations."""
    return {
        "presentations": [
            {
                "id": pres_id,
                "slide_count": len(pres.slides),
                "is_current": pres_id == current_presentation_id
            }
            for pres_id, pres in presentations.items()
        ],
        "current_presentation_id": current_presentation_id,
        "total_presentations": len(presentations)
    }
@mcp_app.tool()
def switch_presentation(presentation_id: str) -> Dict:
    """Switch to a different loaded presentation."""
    if presentation_id not in presentations:
        return {
            "error": f"Presentation '{presentation_id}' not found. Available presentations: {list(presentations.keys())}"
        }
    
    global current_presentation_id
    old_id = current_presentation_id
    current_presentation_id = presentation_id
    
    return {
        "message": f"Switched from presentation '{old_id}' to '{presentation_id}'",
        "previous_presentation_id": old_id,
        "current_presentation_id": current_presentation_id
    }
@mcp_app.tool()
def get_server_info() -> Dict:
    """Get information about the MCP server."""
    return {
        "name": "PowerPoint MCP Server - Enhanced Edition",
        "version": "2.1.0",
        "total_tools": 32,
        "loaded_presentations": len(presentations),
        "current_presentation": current_presentation_id,
        "transport": "streamable-http",
        "features": [
            "Presentation Management (7 tools)",
            "Content Management (6 tools)", 
            "Template Operations (7 tools)",
            "Structural Elements (4 tools)",
            "Professional Design (3 tools)",
            "Specialized Features (5 tools)"
        ]
    }
# Direct tool usage functions for Gradio (using internal MCP mechanisms)
def create_test_presentation():
    """Create a test presentation using MCP tools directly"""
    from pptx import Presentation
    from pptx.util import Inches
    import uuid
    
    try:
        # Create presentation directly
        prs = Presentation()
        presentation_id = str(uuid.uuid4())
        presentations[presentation_id] = prs
        set_current_presentation_id(presentation_id)
        
        return presentation_id, "โœ… Test presentation created successfully"
    except Exception as e:
        return None, f"โŒ Error creating presentation: {str(e)}"
def add_test_slide(presentation_id, title="Test Slide", content="Test content"):
    """Add a test slide"""
    try:
        if presentation_id not in presentations:
            return False, "Presentation not found"
        
        prs = presentations[presentation_id]
        
        # Add slide with title and content layout
        slide_layout = prs.slide_layouts[1]  # Title and content layout
        slide = prs.slides.add_slide(slide_layout)
        
        # Set title
        if slide.shapes.title:
            slide.shapes.title.text = title
        
        # Set content
        if len(slide.placeholders) > 1:
            slide.placeholders[1].text = content
        
        return True, f"Slide added: {title}"
    except Exception as e:
        return False, f"Error adding slide: {str(e)}"
def save_test_presentation(presentation_id):
    """Save test presentation to file"""
    try:
        if presentation_id not in presentations:
            return None, "Presentation not found"
        
        prs = presentations[presentation_id]
        temp_file = tempfile.NamedTemporaryFile(suffix='.pptx', delete=False)
        prs.save(temp_file.name)
        
        return temp_file.name, "โœ… Presentation saved successfully"
    except Exception as e:
        return None, f"โŒ Error saving presentation: {str(e)}"
# Gradio Interface Functions
def create_presentation_from_json(slides_data):
    """Create PowerPoint from JSON data (for Gradio testing)"""
    try:
        if isinstance(slides_data, str):
            data = json.loads(slides_data)
        else:
            data = slides_data
        
        # Create presentation
        presentation_id, create_message = create_test_presentation()
        if not presentation_id:
            return None, create_message
        
        # Add slides
        slide_count = 0
        for slide_info in data.get("slides", []):
            success, message = add_test_slide(
                presentation_id,
                slide_info.get("title", f"Slide {slide_count + 1}"),
                slide_info.get("content", "Sample content")
            )
            if success:
                slide_count += 1
        
        if slide_count == 0:
            return None, "โŒ No slides were created successfully"
        
        # Save presentation
        file_path, save_message = save_test_presentation(presentation_id)
        
        if file_path:
            return file_path, f"โœ… Presentation created with {slide_count} slides"
        else:
            return None, save_message
            
    except Exception as e:
        logger.error(f"Error creating presentation: {str(e)}")
        return None, f"โŒ Error: {str(e)}"
def get_server_status():
    """Get current server status for display"""
    return f"""
๐ŸŸข **Server Status**: Running
๐Ÿ”ง **Transport**: Streamable HTTP  
๐Ÿ“ฆ **Tools Available**: 32+ (All modules registered)
๐ŸŽฏ **MCP Version**: 2024-11-05
โšก **Server Version**: 2.1.0
๐Ÿ“Š **Presentations Loaded**: {len(presentations)}
๐ŸŽฎ **Current Presentation**: {current_presentation_id or 'None'}
"""
# Create Gradio Interface
def create_gradio_interface():
    """Create the main Gradio interface"""
    
    with gr.Blocks(title="PowerPoint MCP Server - Streamable HTTP", theme=gr.themes.Soft()) as demo:
        gr.Markdown("# ๐ŸŽฏ PowerPoint MCP Server")
        gr.Markdown("**Transport**: Streamable HTTP | **Endpoint**: `/mcp` | **Tools**: 32+ available")
        
        with gr.Tab("๐Ÿš€ Test Interface"):
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### Create Presentation from JSON")
                    slides_input = gr.Textbox(
                        label="Slides Data (JSON)",
                        value='{"slides": [{"title": "Welcome", "content": "This is slide 1"}, {"title": "About Us", "content": "This is slide 2"}]}',
                        lines=12,
                        placeholder='{"slides": [{"title": "Slide Title", "content": "Slide content"}]}'
                    )
                    create_btn = gr.Button("๐Ÿš€ Create Presentation", variant="primary", size="lg")
                
                with gr.Column():
                    status_output = gr.Textbox(
                        label="Creation Status", 
                        interactive=False,
                        lines=3
                    )
                    download_btn = gr.DownloadButton(
                        label="๐Ÿ“ฅ Download PowerPoint",
                        visible=False,
                        size="lg"
                    )
        
        with gr.Tab("๐Ÿ”ง MCP Configuration"):
            gr.Markdown("## MCP Server Settings for Your Chatbot")
            
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### Configuration Details")
                    config_code = f"""**Name**: PowerPoint Creator
**Description**: AI-powered PowerPoint presentation generator with 32 professional tools and streamable HTTP transport
**URL**: https://brucewayne1-auxoppt.hf.space/mcp
**Transport**: Stream"""
                    gr.Code(config_code, language="yaml")
                
                with gr.Column():
                    gr.Markdown("### Quick Copy")
                    gr.Textbox(
                        value="https://brucewayne1-auxoppt.hf.space/mcp",
                        label="MCP Server URL",
                        interactive=True
                    )
                    gr.Textbox(
                        value="Stream",
                        label="Transport Type",
                        interactive=False
                    )
        
        with gr.Tab("๐Ÿ“Š Server Status"):
            status_text = gr.Textbox(
                value=get_server_status(),
                label="Server Information",
                lines=10,
                interactive=False
            )
            
            refresh_btn = gr.Button("๐Ÿ”„ Refresh Status", variant="secondary")
            
            refresh_btn.click(
                fn=get_server_status,
                outputs=[status_text]
            )
        
        with gr.Tab("๐Ÿ“– Available Tools"):
            gr.Markdown("## All Available MCP Tools")
            
            tools_info = """
### ๐ŸŽฏ Presentation Management (7 tools)
โ€ข create_presentation โ€ข create_presentation_from_template โ€ข open_presentation
โ€ข save_presentation โ€ข get_presentation_info โ€ข get_template_file_info โ€ข set_core_properties
### ๐Ÿ“ Content Management (6 tools) 
โ€ข add_slide โ€ข get_slide_info โ€ข extract_slide_text โ€ข extract_presentation_text
โ€ข populate_placeholder โ€ข add_bullet_points โ€ข manage_text โ€ข manage_image
### ๐ŸŽจ Template Operations (7 tools)
โ€ข list_slide_templates โ€ข apply_slide_template โ€ข create_slide_from_template
โ€ข create_presentation_from_templates โ€ข get_template_info โ€ข auto_generate_presentation โ€ข optimize_slide_text
### ๐Ÿ—๏ธ Structural Elements (4 tools)
โ€ข add_table โ€ข format_table_cell โ€ข add_shape โ€ข add_chart
### โœจ Professional Design (3 tools)
โ€ข apply_professional_design โ€ข apply_picture_effects โ€ข manage_fonts
### ๐Ÿ”ง Specialized Features (5 tools)
โ€ข manage_hyperlinks โ€ข manage_slide_masters โ€ข add_connector โ€ข update_chart_data โ€ข manage_slide_transitions
            """
            gr.Markdown(tools_info)
        
        # Event handlers
        create_btn.click(
            fn=create_presentation_from_json,
            inputs=[slides_input],
            outputs=[download_btn, status_output]
        ).then(
            fn=lambda x: gr.update(visible=bool(x)),
            inputs=[download_btn],
            outputs=[download_btn]
        )
    
    return demo
# MCP Server startup function
def start_mcp_server():
    """Start the MCP server with streamable HTTP transport"""
    try:
        logger.info("Starting MCP Server with streamable HTTP transport...")
        # Use streamable HTTP transport on port 8000
        mcp_app.run(transport='streamable-http', port=8000)
    except Exception as e:
        logger.error(f"Failed to start MCP server: {str(e)}")
# Main execution
if __name__ == "__main__":
    # Start MCP server in background thread
    mcp_thread = Thread(target=start_mcp_server, daemon=True)
    mcp_thread.start()
    
    # Wait for MCP server to start
    time.sleep(3)
    logger.info("MCP Server started on port 8000 with streamable HTTP transport")
    
    # Launch Gradio interface
    demo = create_gradio_interface()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True,
        show_error=True,
        show_api=False
    )