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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
OpenManus - Complete Production Version for HuggingFace Spaces
Includes: Mobile Authentication + All AI Models + Cloudflare Services (D1, R2, KV, Durable Objects)
"""

import os
import sys
import sqlite3
import logging
import asyncio
from pathlib import Path
from typing import Optional, Dict, Any

# Add the app directory to Python path
sys.path.append(os.path.join(os.path.dirname(__file__), "app"))

# Import comprehensive configurations
from app.production_config import OpenManusConfig, config

# Configure logging
logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)


class OpenManusProduction:
    """Complete OpenManus production application with all services"""

    def __init__(self):
        self.db_path = Path("auth.db")
        self.cloudflare_client = None
        self.d1_db = None
        self.r2_storage = None
        self.kv_storage = None
        self.durable_objects = None
        self.manus_agent = None
        self.initialized = False

    def setup_database(self):
        """Initialize SQLite database for authentication"""
        try:
            # Create database if it doesn't exist
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()

            # Create users table with mobile number authentication
            cursor.execute(
                """
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                mobile_number TEXT UNIQUE NOT NULL,
                full_name TEXT NOT NULL,
                password_hash TEXT NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                last_login TIMESTAMP
            )
            """
            )

            # Create sessions table
            cursor.execute(
                """
            CREATE TABLE IF NOT EXISTS sessions (
                id TEXT PRIMARY KEY,
                user_id INTEGER NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                expires_at TIMESTAMP NOT NULL,
                FOREIGN KEY (user_id) REFERENCES users (id)
            )
            """
            )

            # Create agent interactions log
            cursor.execute(
                """
            CREATE TABLE IF NOT EXISTS agent_interactions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER NOT NULL,
                session_id TEXT NOT NULL,
                model_used TEXT,
                input_text TEXT,
                output_text TEXT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users (id)
            )
            """
            )

            conn.commit()
            conn.close()
            logger.info("Database initialized successfully")
            return True

        except Exception as e:
            logger.error(f"Database setup failed: {e}")
            return False

    async def init_cloudflare_services(self):
        """Initialize all Cloudflare services"""
        try:
            # Get Cloudflare credentials from environment
            cf_token = os.getenv("CLOUDFLARE_API_TOKEN")
            cf_account_id = os.getenv("CLOUDFLARE_ACCOUNT_ID")
            cf_worker_url = os.getenv("CLOUDFLARE_WORKER_URL")

            if cf_token and cf_account_id:
                logger.info("Initializing Cloudflare services...")

                # Import Cloudflare services
                from cloudflare import (
                    CloudflareClient,
                    D1Database,
                    R2Storage,
                    KVStorage,
                    DurableObjects,
                )

                # Initialize client
                self.cloudflare_client = CloudflareClient(
                    api_token=cf_token,
                    account_id=cf_account_id,
                    worker_url=cf_worker_url,
                )

                # Initialize D1 Database
                if os.getenv("CLOUDFLARE_D1_DATABASE_ID"):
                    self.d1_db = D1Database(
                        client=self.cloudflare_client,
                        database_id=os.getenv("CLOUDFLARE_D1_DATABASE_ID"),
                    )
                    logger.info("D1 Database service initialized")

                # Initialize R2 Storage
                if os.getenv("CLOUDFLARE_R2_BUCKET_NAME"):
                    self.r2_storage = R2Storage(
                        client=self.cloudflare_client,
                        bucket_name=os.getenv("CLOUDFLARE_R2_BUCKET_NAME"),
                    )
                    logger.info("R2 Storage service initialized")

                # Initialize KV Storage
                if os.getenv("CLOUDFLARE_KV_NAMESPACE_ID"):
                    self.kv_storage = KVStorage(
                        client=self.cloudflare_client,
                        namespace_id=os.getenv("CLOUDFLARE_KV_NAMESPACE_ID"),
                    )
                    logger.info("KV Storage service initialized")

                # Initialize Durable Objects
                self.durable_objects = DurableObjects(self.cloudflare_client)
                logger.info("Durable Objects service initialized")

                logger.info("All Cloudflare services initialized successfully")

            else:
                logger.warning(
                    "Cloudflare credentials not provided, running in local mode"
                )

        except Exception as e:
            logger.error(f"Cloudflare services initialization failed: {e}")
            logger.info("Continuing in local mode...")

    async def init_ai_agent(self):
        """Initialize the Manus AI agent with all models"""
        try:
            logger.info("Initializing AI Agent with all HuggingFace models...")

            # Import the agent and models
            from app.agent.manus import Manus
            from app.huggingface_models import HuggingFaceModels

            # Initialize HuggingFace models with comprehensive configuration
            hf_models = HuggingFaceModels()

            # Load all model categories from config
            total_models = 0
            for category_name, models in [
                ("text-generation", config.categories.TEXT_GENERATION_MODELS),
                ("image-editing", config.categories.IMAGE_EDITING_MODELS),
                ("speech", config.categories.SPEECH_MODELS),
                ("face-swap", config.categories.FACE_SWAP_MODELS),
                ("avatar", config.categories.AVATAR_MODELS),
                ("arabic-english", config.categories.ARABIC_ENGLISH_MODELS),
            ]:
                logger.info(f"Loading {len(models)} models for {category_name}")
                total_models += len(models)

            # Initialize with all services and comprehensive model configuration
            self.manus_agent = await Manus.create(
                d1_db=self.d1_db,
                r2_storage=self.r2_storage,
                kv_storage=self.kv_storage,
                durable_objects=self.durable_objects,
            )

            logger.info(
                f"AI Agent initialized with {total_models}+ models across all categories"
            )

        except Exception as e:
            logger.error(f"AI Agent initialization failed: {e}")
            logger.info("Creating fallback agent...")

            # Create a simple fallback agent
            class FallbackAgent:
                async def process_message(
                    self, message: str, user_id: Optional[str] = None
                ) -> str:
                    return f"Fallback response for: {message}"

            self.manus_agent = FallbackAgent()

    def create_gradio_interface(self):
        """Create the complete Gradio interface with all features"""
        try:
            import gradio as gr

            # Import authentication components
            from auth_service import AuthService
            from auth import UserSignupRequest, UserLoginRequest

            auth_service = AuthService()

            # Authentication functions
            async def handle_signup(
                mobile_number: str, full_name: str, password: str, confirm_password: str
            ):
                try:
                    if password != confirm_password:
                        return "❌ Passwords do not match"

                    signup_request = UserSignupRequest(
                        mobile_number=mobile_number,
                        full_name=full_name,
                        password=password,
                        confirm_password=confirm_password,
                    )

                    success, message = await auth_service.register_user(signup_request)
                    return f"{'βœ…' if success else '❌'} {message}"

                except Exception as e:
                    return f"❌ Signup error: {str(e)}"

            async def handle_login(mobile_number: str, password: str):
                try:
                    login_request = UserLoginRequest(
                        mobile_number=mobile_number, password=password
                    )

                    user, session = await auth_service.login_user(login_request)
                    if user and session:
                        return f"βœ… Welcome {user.full_name}!", user.dict(), session.id
                    else:
                        return "❌ Invalid credentials", None, None

                except Exception as e:
                    return f"❌ Login error: {str(e)}", None, None

            async def handle_ai_message(
                message: str, history: list, user_data: dict, session_id: str
            ):
                try:
                    if not user_data or not session_id:
                        return (
                            history
                            + [
                                ("You", message),
                                (
                                    "Assistant",
                                    "Please log in first to use the AI assistant.",
                                ),
                            ],
                            "",
                        )

                    # Process message through AI agent
                    response = await self.manus_agent.process_message(
                        message, user_data.get("id")
                    )

                    # Add to history
                    history.append(("You", message))
                    history.append(("Assistant", response))

                    return history, ""

                except Exception as e:
                    error_msg = f"AI processing error: {str(e)}"
                    history.append(("You", message))
                    history.append(("Assistant", error_msg))
                    return history, ""

            # Create the interface
            with gr.Blocks(
                title="OpenManus - Complete AI Platform",
                theme=gr.themes.Soft(),
                css="""
                .container { max-width: 1200px; margin: 0 auto; }
                .auth-section { background: #f8f9fa; padding: 20px; border-radius: 10px; margin: 10px 0; }
                .chat-section { background: #ffffff; padding: 20px; border-radius: 10px; margin: 10px 0; }
                .status-box { background: #e8f5e8; padding: 15px; border-radius: 8px; margin: 10px 0; }
                """,
            ) as demo:

                # Header
                gr.HTML(
                    """
                <div style="text-align: center; padding: 20px;">
                    <h1>πŸ€– OpenManus - Complete AI Platform</h1>
                    <p>Mobile Authentication + 200+ AI Models + Cloudflare Services</p>
                </div>
                """
                )

                # State variables
                user_state = gr.State(None)
                session_state = gr.State(None)

                with gr.Row():
                    # Authentication Column
                    with gr.Column(scale=1, elem_classes="auth-section"):
                        gr.Markdown("## πŸ” Authentication")

                        with gr.Tab("Sign Up"):
                            signup_mobile = gr.Textbox(
                                label="Mobile Number", placeholder="+1234567890"
                            )
                            signup_name = gr.Textbox(
                                label="Full Name", placeholder="Your full name"
                            )
                            signup_password = gr.Textbox(
                                label="Password", type="password"
                            )
                            signup_confirm = gr.Textbox(
                                label="Confirm Password", type="password"
                            )
                            signup_btn = gr.Button("Sign Up", variant="primary")
                            signup_output = gr.Textbox(
                                label="Result", interactive=False
                            )

                            signup_btn.click(
                                handle_signup,
                                [
                                    signup_mobile,
                                    signup_name,
                                    signup_password,
                                    signup_confirm,
                                ],
                                signup_output,
                            )

                        with gr.Tab("Login"):
                            login_mobile = gr.Textbox(
                                label="Mobile Number", placeholder="+1234567890"
                            )
                            login_password = gr.Textbox(
                                label="Password", type="password"
                            )
                            login_btn = gr.Button("Login", variant="primary")
                            login_output = gr.Textbox(label="Result", interactive=False)

                            login_btn.click(
                                handle_login,
                                [login_mobile, login_password],
                                [login_output, user_state, session_state],
                            )

                    # AI Chat Column
                    with gr.Column(scale=2, elem_classes="chat-section"):
                        gr.Markdown("## πŸ€– AI Assistant (200+ Models)")

                        chatbot = gr.Chatbot(
                            label="Chat with OpenManus AI",
                            height=500,
                            show_copy_button=True,
                        )

                        with gr.Row():
                            msg_input = gr.Textbox(
                                label="Message",
                                placeholder="Type your message here... (Login required)",
                                scale=4,
                            )
                            send_btn = gr.Button("Send", variant="primary", scale=1)

                        # File upload for images/documents
                        file_upload = gr.File(
                            label="Upload Files (Images, Documents)",
                            file_types=["image", "text", ".pdf", ".docx"],
                        )

                        # Send message
                        send_btn.click(
                            handle_ai_message,
                            [msg_input, chatbot, user_state, session_state],
                            [chatbot, msg_input],
                        )

                        msg_input.submit(
                            handle_ai_message,
                            [msg_input, chatbot, user_state, session_state],
                            [chatbot, msg_input],
                        )

                # Status Section
                with gr.Row():
                    with gr.Column(elem_classes="status-box"):
                        gr.HTML(
                            """
                        <div>
                            <h3>πŸš€ Platform Status</h3>
                            <ul>
                                <li>βœ… Authentication System: Active</li>
                                <li>βœ… AI Models: 200+ Available</li>
                                <li>βœ… HuggingFace Integration: Active</li>
                                <li>πŸ”„ Cloudflare Services: Dynamic</li>
                            </ul>
                        </div>
                        """
                        )

            return demo

        except Exception as e:
            logger.error(f"Gradio interface creation failed: {e}")

            # Create emergency fallback interface
            import gradio as gr

            with gr.Blocks(title="OpenManus - Emergency Mode") as fallback_demo:
                gr.Markdown(
                    f"""
                # ⚠️ OpenManus - Emergency Mode

                **Error:** {str(e)}

                The system is running in emergency mode. Basic functionality may be limited.
                """
                )

                with gr.Row():
                    emergency_input = gr.Textbox(label="Test Input")
                    emergency_output = gr.Textbox(label="Test Output")
                    emergency_btn = gr.Button("Test")

                def emergency_test(text):
                    return f"Emergency response: {text}"

                emergency_btn.click(emergency_test, emergency_input, emergency_output)

            return fallback_demo

    async def initialize(self):
        """Initialize all services"""
        if self.initialized:
            return True

        try:
            logger.info("πŸš€ Starting OpenManus Production initialization...")

            # Setup database
            if not self.setup_database():
                logger.error("Database setup failed")
                return False

            # Initialize Cloudflare services
            await self.init_cloudflare_services()

            # Initialize AI agent
            await self.init_ai_agent()

            self.initialized = True
            logger.info("βœ… OpenManus Production fully initialized")
            return True

        except Exception as e:
            logger.error(f"Initialization failed: {e}")
            return False

    def launch(self):
        """Launch the complete application"""
        try:
            # Create interface
            app = self.create_gradio_interface()

            # Launch for HuggingFace Spaces
            logger.info("🌟 Launching OpenManus Production on port 7860...")

            app.launch(
                server_name="0.0.0.0",
                server_port=7860,
                share=False,
                show_api=False,
                quiet=False,
                inbrowser=False,
                allowed_paths=["./assets", "./workspace"],
            )

        except Exception as e:
            logger.error(f"Launch failed: {e}")
            raise


async def main():
    """Main function"""
    app = OpenManusProduction()

    # Initialize all services
    success = await app.initialize()

    if success:
        logger.info("βœ… All services initialized successfully")
    else:
        logger.warning(
            "⚠️ Some services failed to initialize, continuing with available services"
        )

    # Launch the application
    app.launch()


if __name__ == "__main__":
    asyncio.run(main())