Chris4K commited on
Commit
7d4cb9c
·
verified ·
1 Parent(s): 87532e2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -254
app.py CHANGED
@@ -1,254 +1,120 @@
1
- #!/usr/bin/env python3
2
- """
3
- MMORPG Application - Refactored Clean Architecture
4
- Main application entry point using clean architecture principles
5
- """
6
-
7
- import gradio as gr
8
- import asyncio
9
- import threading
10
- from typing import Optional
11
- import os
12
- import uvicorn
13
- from gradio.routes import App
14
-
15
- # Import our clean architecture components
16
- from src.core.game_engine import GameEngine
17
- from src.facades.game_facade import GameFacade
18
- from src.ui.huggingface_ui import HuggingFaceUI
19
- from src.ui.improved_interface_manager import ImprovedInterfaceManager
20
- from src.mcp.mcp_tools import GradioMCPTools
21
-
22
- class MMORPGApplication:
23
- """Main application class that orchestrates the MMORPG game."""
24
-
25
- def __init__(self):
26
- """Initialize the application with all necessary components."""
27
- # Initialize core game engine (singleton)
28
- self.game_engine = GameEngine()
29
- # Initialize game facade for simplified operations
30
- self.game_facade = GameFacade()
31
-
32
- # Initialize UI components
33
- self.ui = HuggingFaceUI(self.game_facade)
34
- self.interface_manager = ImprovedInterfaceManager(self.game_facade, self.ui)
35
-
36
- # Initialize MCP tools for AI agent integration
37
- self.mcp_tools = GradioMCPTools(self.game_facade)
38
-
39
- # Gradio interface reference
40
- self.gradio_interface: Optional[gr.Blocks] = None
41
-
42
- # Background tasks
43
- self._cleanup_task = None
44
- self._auto_refresh_task = None
45
-
46
- def create_gradio_interface(self) -> gr.Blocks:
47
- """Create and configure the Gradio interface."""
48
- # Use the ImprovedInterfaceManager to create the complete interface with proper event handling
49
- self.gradio_interface = self.interface_manager.create_interface()
50
- return self.gradio_interface
51
-
52
- def start_background_tasks(self):
53
- """Start background tasks for game maintenance."""
54
-
55
- def cleanup_task():
56
- """Background task for cleaning up inactive players."""
57
- while True:
58
- try:
59
- self.game_facade.cleanup_inactive_players()
60
- threading.Event().wait(30) # Wait 30 seconds
61
- except Exception as e:
62
- print(f"Error in cleanup task: {e}")
63
- threading.Event().wait(5) # Wait before retry
64
-
65
- def auto_refresh_task():
66
- """Background task for auto-refreshing game state."""
67
- while True:
68
- try:
69
- # Trigger refresh for active sessions
70
- # This would need session tracking for real implementation
71
- threading.Event().wait(2) # Refresh every 2 seconds
72
- except Exception as e:
73
- print(f"Error in auto-refresh task: {e}")
74
- threading.Event().wait(5) # Wait before retry
75
-
76
- # Start cleanup task
77
- self._cleanup_task = threading.Thread(target=cleanup_task, daemon=True)
78
- self._cleanup_task.start()
79
-
80
- # Start auto-refresh task
81
- self._auto_refresh_task = threading.Thread(target=auto_refresh_task, daemon=True)
82
- self._auto_refresh_task.start()
83
-
84
- def run(self, share: bool = False, server_port: int = 7860):
85
- """Run the MMORPG application."""
86
- print("🎮 Starting MMORPG Application...")
87
- print("🏗️ Initializing game engine...")
88
- # Initialize game world and services
89
- if not self.game_engine.start():
90
- print("❌ Failed to start game engine")
91
- return
92
-
93
- print("🎨 Creating user interface...")
94
-
95
- # Create Gradio interface
96
- interface = self.create_gradio_interface()
97
-
98
- print("🔧 Starting background tasks...")
99
-
100
- # Start background maintenance tasks
101
- self.start_background_tasks()
102
-
103
- print("🚀 Launching server...")
104
- print(f"🌐 Server will be available at: http://localhost:{server_port}")
105
-
106
- if share:
107
- print("🔗 Public URL will be generated...")
108
- # Launch the interface
109
- interface.launch(
110
- share=share,
111
- debug=True,
112
- server_port=server_port,
113
- mcp_server=True, # Enable MCP server integration
114
- show_error=True,
115
- quiet=False
116
- )
117
-
118
- def launch_with_fallback(self, share: bool = False, server_port: int = 7860):
119
- """Launch with multiple fallback options for ASGI errors."""
120
-
121
- # Get the interface first
122
- interface = self.create_gradio_interface()
123
-
124
- try:
125
- # Method 1: Standard MCP launch
126
- print("Attempting standard MCP launch...")
127
- interface.launch(
128
- mcp_server=True,
129
- debug=True,
130
- share=share,
131
- server_port=server_port,
132
- show_error=False, # Reduce error display that can cause ASGI issues
133
- prevent_thread_lock=False
134
- )
135
-
136
- except Exception as e:
137
- print(f"Standard MCP launch failed: {e}")
138
-
139
- try:
140
- # Method 2: Launch with specific ASGI settings
141
- print("Attempting launch with ASGI workarounds...")
142
-
143
- # Set environment variables for better ASGI handling
144
- os.environ['GRADIO_SERVER_NAME'] = '0.0.0.0'
145
- os.environ['GRADIO_SERVER_PORT'] = str(server_port)
146
- os.environ['GRADIO_DEBUG'] = 'false'
147
-
148
- interface.launch(
149
- mcp_server=True,
150
- debug=False,
151
- share=share,
152
- auth=None,
153
- max_threads=10
154
- )
155
-
156
- except Exception as e2:
157
- print(f"ASGI workaround failed: {e2}")
158
-
159
- try:
160
- # Method 3: Manual Uvicorn launch
161
- print("Attempting manual Uvicorn launch...")
162
-
163
- # Get the FastAPI app from Gradio
164
- app = interface.app
165
-
166
- # Configure Uvicorn with specific settings for MCP
167
- config = uvicorn.Config(
168
- app=app,
169
- host="0.0.0.0",
170
- port=server_port,
171
- log_level="info",
172
- access_log=False,
173
- server_header=False,
174
- date_header=False,
175
- loop="asyncio",
176
- timeout_keep_alive=30,
177
- timeout_notify=30,
178
- limit_concurrency=100,
179
- limit_max_requests=1000
180
- )
181
-
182
- server = uvicorn.Server(config)
183
- server.run()
184
-
185
- except Exception as e3:
186
- print(f"Manual Uvicorn launch failed: {e3}")
187
-
188
- # Method 4: Fallback to regular Gradio (no MCP)
189
- print("Falling back to regular Gradio without MCP...")
190
- interface.launch(
191
- debug=False,
192
- share=share,
193
- server_port=server_port,
194
- show_error=True
195
- )
196
-
197
- def launch_with_threading(self, share: bool = False, server_port: int = 7860):
198
- """Launch using threading to avoid asyncio event loop conflicts."""
199
-
200
- # Get the interface first
201
- interface = self.create_gradio_interface()
202
-
203
- def run_server():
204
- try:
205
- # Create new event loop for this thread
206
- loop = asyncio.new_event_loop()
207
- asyncio.set_event_loop(loop)
208
-
209
- interface.launch(
210
- mcp_server=True,
211
- debug=True,
212
- share=share,
213
- server_port=server_port,
214
- prevent_thread_lock=False
215
- )
216
- except Exception as e:
217
- print(f"Threading launch failed: {e}")
218
- # Fallback without MCP
219
- interface.launch(debug=False, share=share, server_port=server_port)
220
-
221
- # Start server in separate thread
222
- server_thread = threading.Thread(target=run_server, daemon=True)
223
- server_thread.start()
224
- server_thread.join()
225
-
226
- def main():
227
- """Main entry point for the application."""
228
- # Create and run the application
229
- app = MMORPGApplication()
230
-
231
- # Check if running on HuggingFace Spaces
232
- if os.getenv("SPACE_ID"):
233
- print("Running on HuggingFace Spaces")
234
- # Use more conservative settings for Spaces
235
- try:
236
- interface = app.create_gradio_interface()
237
- interface.launch(
238
- mcp_server=True,
239
- debug=True,
240
- share=True,
241
- show_error=False,
242
- server_port=int(os.getenv("PORT", 7860))
243
- )
244
- except:
245
- # Fallback for Spaces
246
- interface = app.create_gradio_interface()
247
- interface.launch(share=False, debug=False)
248
- else:
249
- # Local development
250
- print("Running locally with enhanced launcher")
251
- app.run(share=True, server_port=7869)
252
-
253
- if __name__ == "__main__":
254
- main()
 
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
+ with gr.Blocks(title="MMORPG - Limited Mode") as interface:
21
+ gr.Markdown("""
22
+ # 🎮 MMORPG Application - Limited Mode
23
+
24
+ **Note:** Running in limited mode due to import issues.
25
+
26
+ This is a simplified version that focuses on core functionality.
27
+ """)
28
+
29
+ with gr.Tab("🔍 SearchHF Oracle"):
30
+ gr.Markdown("""
31
+ ## 🔍 SearchHF Oracle
32
+
33
+ Advanced Hugging Face search using MCP integration.
34
+ """)
35
+
36
+ query_input = gr.Textbox(
37
+ label="Search Query",
38
+ placeholder="e.g., 'text-generation models'"
39
+ )
40
+ search_btn = gr.Button("🔍 Search", variant="primary")
41
+ search_output = gr.Textbox(
42
+ label="Search Results",
43
+ lines=10,
44
+ interactive=False
45
+ )
46
+
47
+ def simple_search(query):
48
+ if not query.strip():
49
+ return "❌ Please enter a search query"
50
+ return f"🔍 **Search Results for:** {query}\n\n⚠️ Full MCP integration not available in this environment.\n\nTo use full functionality, please run locally."
51
+
52
+ search_btn.click(
53
+ simple_search,
54
+ inputs=[query_input],
55
+ outputs=[search_output]
56
+ )
57
+
58
+ with gr.Tab("ℹ️ About"):
59
+ gr.Markdown("""
60
+ # About MMORPG Application
61
+
62
+ This is an AI-powered MMORPG with:
63
+ - **MCP Integration** - Model Context Protocol for AI agents
64
+ - **Dynamic NPCs** - AI-powered non-player characters
65
+ - **Plugin System** - Extensible addon architecture
66
+ - **Real-time Chat** - Multi-channel communication
67
+ - **Trading System** - Virtual economy
68
+
69
+ ## 🚀 Full Version
70
+
71
+ For the complete experience with all features, please run the application locally.
72
+
73
+ ## 🔧 Technical Details
74
+
75
+ - **Framework:** Gradio + Python
76
+ - **AI Integration:** MCP (Model Context Protocol)
77
+ - **Architecture:** Clean architecture with dependency injection
78
+ """)
79
+
80
+ return interface
81
+
82
+ def main():
83
+ """Main application entry point for HuggingFace Spaces."""
84
+ try:
85
+ # Try to import the full application
86
+ from src.core.game_engine import GameEngine
87
+ from src.facades.game_facade import GameFacade
88
+ from src.ui.huggingface_ui import HuggingFaceUI
89
+ from src.ui.improved_interface_manager import ImprovedInterfaceManager
90
+ from src.mcp.mcp_tools import GradioMCPTools
91
+
92
+ # Initialize full application
93
+ game_engine = GameEngine()
94
+ game_facade = GameFacade()
95
+ ui = HuggingFaceUI(game_facade)
96
+ interface_manager = ImprovedInterfaceManager(game_facade, ui)
97
+
98
+ # Create the complete interface
99
+ interface = interface_manager.create_interface()
100
+
101
+ print("✅ Full MMORPG application loaded successfully!")
102
+
103
+ except Exception as e:
104
+ print(f"⚠️ Failed to load full application: {e}")
105
+ print("🔄 Falling back to limited mode...")
106
+
107
+ # Create fallback interface
108
+ interface = create_fallback_interface()
109
+
110
+ # Launch the interface
111
+ interface.launch(
112
+ #server_name="0.0.0.0",
113
+ #server_port=7860, # Standard HF port
114
+ share=True,
115
+ debug=True,
116
+ # quiet=False
117
+ )
118
+
119
+ if __name__ == "__main__":
120
+ main()