Chris4K commited on
Commit
6f37a99
·
verified ·
1 Parent(s): 17055d1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -109
app.py CHANGED
@@ -1,129 +1,117 @@
1
- #!/usr/bin/env python3
2
- """
3
- MMORPG Application - HuggingFace Space Version
4
- Simplified version for HuggingFace deployment with fallback imports
5
- """
6
-
7
  import gradio as gr
8
  import asyncio
9
- import os
10
- import sys
11
  from typing import Optional
12
 
13
- # Add current directory to Python path for HF Spaces
14
- current_dir = os.path.dirname(os.path.abspath(__file__))
15
- if current_dir not in sys.path:
16
- sys.path.insert(0, current_dir)
 
 
17
 
18
- def create_fallback_interface():
19
- """Create a fallback interface if main components fail to load."""
20
 
21
- # Try to import the simple SearchHF interface
22
- try:
23
- from simple_searchhf import create_searchhf_interface
24
- return create_searchhf_interface()
25
- except ImportError:
26
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- # Create basic fallback if even simple interface fails
29
- with gr.Blocks(title="MMORPG - Limited Mode") as interface:
30
- gr.Markdown("""
31
- # 🎮 MMORPG Application - Limited Mode
32
 
33
- **Note:** Running in limited mode due to import issues.
 
 
 
 
 
 
 
 
34
 
35
- This is a simplified version that focuses on core functionality.
36
- """)
 
 
 
 
 
 
 
 
37
 
38
- with gr.Tab("🔍 SearchHF Oracle"):
39
- gr.Markdown("""
40
- ## 🔍 SearchHF Oracle
41
-
42
- Advanced Hugging Face search using MCP integration.
43
- """)
44
-
45
- query_input = gr.Textbox(
46
- label="Search Query",
47
- placeholder="e.g., 'text-generation models'"
48
- )
49
- search_btn = gr.Button("🔍 Search", variant="primary")
50
- search_output = gr.Textbox(
51
- label="Search Results",
52
- lines=10,
53
- interactive=False
54
- )
55
-
56
- def simple_search(query):
57
- if not query.strip():
58
- return "❌ Please enter a search query"
59
- return f"🔍 **Search Results for:** {query}\n\n⚠️ Full MCP integration not available in this environment.\n\nTo use full functionality, please run locally."
60
-
61
- search_btn.click(
62
- simple_search,
63
- inputs=[query_input],
64
- outputs=[search_output]
65
- )
66
 
67
- with gr.Tab("ℹ️ About"):
68
- gr.Markdown("""
69
- # About MMORPG Application
70
-
71
- This is an AI-powered MMORPG with:
72
- - **MCP Integration** - Model Context Protocol for AI agents
73
- - **Dynamic NPCs** - AI-powered non-player characters
74
- - **Plugin System** - Extensible addon architecture
75
- - **Real-time Chat** - Multi-channel communication
76
- - **Trading System** - Virtual economy
77
-
78
- ## 🚀 Full Version
79
-
80
- For the complete experience with all features, please run the application locally.
81
-
82
- ## 🔧 Technical Details
83
-
84
- - **Framework:** Gradio + Python
85
- - **AI Integration:** MCP (Model Context Protocol)
86
- - **Architecture:** Clean architecture with dependency injection
87
- """)
88
 
89
- return interface
90
-
91
- def main():
92
- """Main application entry point for HuggingFace Spaces."""
93
- try:
94
- # Try to import the full application
95
- from src.core.game_engine import GameEngine
96
- from src.facades.game_facade import GameFacade
97
- from src.ui.huggingface_ui import HuggingFaceUI
98
- from src.ui.improved_interface_manager import ImprovedInterfaceManager
99
- from src.mcp.mcp_tools import GradioMCPTools
100
 
101
- # Initialize full application
102
- game_engine = GameEngine()
103
- game_facade = GameFacade()
104
- ui = HuggingFaceUI(game_facade)
105
- interface_manager = ImprovedInterfaceManager(game_facade, ui)
106
 
107
- # Create the complete interface
108
- interface = interface_manager.create_interface()
109
 
110
- print(" Full MMORPG application loaded successfully!")
111
 
112
- except Exception as e:
113
- print(f"⚠️ Failed to load full application: {e}")
114
- print("🔄 Falling back to limited mode...")
115
 
116
- # Create fallback interface
117
- interface = create_fallback_interface()
118
-
119
- # Launch the interface
120
- interface.launch(
121
- #server_name="0.0.0.0",
122
- #server_port=7860, # Standard HF port
123
- share=True,
124
- debug=True,
125
- # quiet=False
126
- )
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
  if __name__ == "__main__":
129
  main()
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import asyncio
3
+ import threading
 
4
  from typing import Optional
5
 
6
+ # Import our clean architecture components
7
+ from src.core.game_engine import GameEngine
8
+ from src.facades.game_facade import GameFacade
9
+ from src.ui.huggingface_ui import HuggingFaceUI
10
+ from src.ui.improved_interface_manager import ImprovedInterfaceManager
11
+ from src.mcp.mcp_tools import GradioMCPTools
12
 
13
+ class MMORPGApplication:
14
+ """Main application class that orchestrates the MMORPG game."""
15
 
16
+ def __init__(self):
17
+ """Initialize the application with all necessary components."""
18
+ # Initialize core game engine (singleton)
19
+ self.game_engine = GameEngine()
20
+
21
+ # Initialize game facade for simplified operations
22
+ self.game_facade = GameFacade() # Initialize UI components
23
+ self.ui = HuggingFaceUI(self.game_facade)
24
+ self.interface_manager = ImprovedInterfaceManager(self.game_facade, self.ui)
25
+
26
+ # Initialize MCP tools for AI agent integration
27
+ self.mcp_tools = GradioMCPTools(self.game_facade)
28
+ # Gradio interface reference
29
+ self.gradio_interface: Optional[gr.Blocks] = None
30
+
31
+ # Background tasks
32
+ self._cleanup_task = None
33
+ self._auto_refresh_task = None
34
+
35
+ def create_gradio_interface(self) -> gr.Blocks:
36
+ """Create and configure the Gradio interface."""
37
+ # Use the ImprovedInterfaceManager to create the complete interface with proper event handling
38
+ self.gradio_interface = self.interface_manager.create_interface()
39
+ return self.gradio_interface
40
 
41
+ def start_background_tasks(self):
42
+ """Start background tasks for game maintenance."""
 
 
43
 
44
+ def cleanup_task():
45
+ """Background task for cleaning up inactive players."""
46
+ while True:
47
+ try:
48
+ self.game_facade.cleanup_inactive_players()
49
+ threading.Event().wait(30) # Wait 30 seconds
50
+ except Exception as e:
51
+ print(f"Error in cleanup task: {e}")
52
+ threading.Event().wait(5) # Wait before retry
53
 
54
+ def auto_refresh_task():
55
+ """Background task for auto-refreshing game state."""
56
+ while True:
57
+ try:
58
+ # Trigger refresh for active sessions
59
+ # This would need session tracking for real implementation
60
+ threading.Event().wait(2) # Refresh every 2 seconds
61
+ except Exception as e:
62
+ print(f"Error in auto-refresh task: {e}")
63
+ threading.Event().wait(5) # Wait before retry
64
 
65
+ # Start cleanup task
66
+ self._cleanup_task = threading.Thread(target=cleanup_task, daemon=True)
67
+ self._cleanup_task.start()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
+ # Start auto-refresh task
70
+ self._auto_refresh_task = threading.Thread(target=auto_refresh_task, daemon=True)
71
+ self._auto_refresh_task.start()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
+ def run(self, share: bool = False, server_port: int = 7860):
74
+ """Run the MMORPG application."""
75
+ print("🎮 Starting MMORPG Application...")
76
+ print("🏗️ Initializing game engine...")
77
+ # Initialize game world and services
78
+ if not self.game_engine.start():
79
+ print("❌ Failed to start game engine")
80
+ return
 
 
 
81
 
82
+ print("🎨 Creating user interface...")
 
 
 
 
83
 
84
+ # Create Gradio interface
85
+ interface = self.create_gradio_interface()
86
 
87
+ print("🔧 Starting background tasks...")
88
 
89
+ # Start background maintenance tasks
90
+ self.start_background_tasks()
 
91
 
92
+ print("🚀 Launching server...")
93
+ print(f"🌐 Server will be available at: http://localhost:{server_port}")
94
+
95
+ if share:
96
+ print("🔗 Public URL will be generated...")
97
+
98
+ # Launch the interface
99
+ interface.launch(
100
+ share=True, #override
101
+ debug=True,
102
+ # server_port=server_port,
103
+ mcp_server=True, # Enable MCP server integration
104
+ show_error=True,
105
+ quiet=False
106
+ )
107
+
108
+ def main():
109
+ """Main entry point for the application."""
110
+ # Create and run the application
111
+ app = MMORPGApplication()
112
+ # Run with default settings
113
+ # Change share=True to make it publicly accessible
114
+ app.run(share=True, server_port=7869)
115
 
116
  if __name__ == "__main__":
117
  main()