File size: 12,862 Bytes
f095630
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Local startup script for ืžืจืื•ืช (Mirrors) application
Handles environment setup and provides fallback options
"""

import os
import sys
import socket
import subprocess
import logging

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

def find_available_port(start_port=7861, max_tries=10):
    """Find an available port starting from start_port"""
    for port in range(start_port, start_port + max_tries):
        try:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.bind(('127.0.0.1', port))
                return port
        except OSError:
            continue
    return start_port

def check_dependencies():
    """Check if required dependencies are installed"""
    required_packages = ['gradio', 'transformers', 'torch']
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package)
            logger.info(f"โœ… {package} is installed")
        except ImportError:
            missing_packages.append(package)
            logger.error(f"โŒ {package} is missing")
    
    if missing_packages:
        logger.error("Missing packages. Please install them:")
        logger.error(f"pip install {' '.join(missing_packages)}")
        return False
    
    return True

def run_simple_app(port):
    """Run the simplified app version"""
    logger.info("๐Ÿ”„ Running simplified version...")
    
    try:
        # Import and run simple app directly
        import gradio as gr
        from conversation_manager import ConversationManager
        from prompt_engineering import DEFAULT_PARTS
        import random

        # Initialize components
        conv_manager = ConversationManager()

        def generate_persona_response(user_message: str, part_name: str, persona_name: str, user_context: str = None):
            """Generate persona-based response using templates"""
            part_info = DEFAULT_PARTS.get(part_name, {})
            display_name = persona_name or part_info.get("default_persona_name", "ื—ืœืง ืคื ื™ืžื™")
            
            # Generate contextual responses based on part type
            if part_name == "ื”ืงื•ืœ ื”ื‘ื™ืงื•ืจืชื™":
                responses = [
                    f"ืื ื™ {display_name}, ื”ืงื•ืœ ื”ื‘ื™ืงื•ืจืชื™ ืฉืœืš. ืฉืžืขืชื™ ืžื” ืฉืืžืจืช ืขืœ '{user_message}' - ืื ื™ ื—ื•ืฉื‘ ืฉืฆืจื™ืš ืœื‘ื—ื•ืŸ ืืช ื–ื” ื™ื•ืชืจ ืœืขื•ืžืง.",
                    f"ืื ื™ {display_name}. ืžื” ืฉืืžืจืช ืžืขื•ืจืจ ื‘ื™ ืฉืืœื•ืช. '{user_message}' - ืื‘ืœ ื”ืื ื–ื” ื‘ืืžืช ื”ืžืฆื‘ ื”ืžืœื?",
                    f"ื–ื” {display_name} ืžื“ื‘ืจ. ืื ื™ ืฉื•ืžืข ืื•ืชืš ืื•ืžืจ '{user_message}', ืื‘ืœ ืื ื™ ืžืจื’ื™ืฉ ืฉืื ื—ื ื• ืฆืจื™ื›ื™ื ืœื”ื™ื•ืช ื™ื•ืชืจ ื‘ื™ืงื•ืจืชื™ื™ื ื›ืืŸ."
                ]
            elif part_name == "ื”ื™ืœื“/ื” ื”ืคื ื™ืžื™ืช":
                responses = [
                    f"ืื ื™ {display_name}, ื”ื™ืœื“/ื” ื”ืคื ื™ืžื™ืช ืฉืœืš. ืžื” ืฉืืžืจืช ืขืœ '{user_message}' ื’ื•ืจื ืœื™ ืœื”ืจื’ื™ืฉ... ืงืฆืช ืคื’ื™ืข.",
                    f"ื–ื” {display_name}. '{user_message}' - ื–ื” ืžื‘ื”ื™ืœ ืื•ืชื™ ืงืฆืช. ืื ื™ ืฆืจื™ืš ืœื“ืขืช ืฉื”ื›ืœ ื™ื”ื™ื” ื‘ืกื“ืจ.",
                    f"ืื ื™ {display_name}, ื”ื—ืœืง ื”ืฆืขื™ืจ ืฉืœืš. ืžื” ืฉืืžืจืช ื ื•ื’ืข ืœืœื‘ ืฉืœื™."
                ]
            elif part_name == "ื”ืžืจืฆื”":
                responses = [
                    f"ืื ื™ {display_name}, ื”ืžืจืฆื” ืฉืœืš. ืฉืžืขืชื™ ืืช '{user_message}' ื•ืื ื™ ืจื•ืฆื” ืœื•ื•ื“ื ืฉื›ื•ืœื ื™ื”ื™ื• ื‘ืกื“ืจ ืขื ื–ื”.",
                    f"ื–ื” {display_name}. ืžื” ืฉืืžืจืช ืขืœ '{user_message}' ื’ื•ืจื ืœื™ ืœื“ืื•ื’ - ื”ืื ื–ื” ื™ื›ื•ืœ ืœืคื’ื•ืข ื‘ืžื™ืฉื”ื•?",
                    f"ืื ื™ {display_name}, ื•ืื ื™ ืจื•ืฆื” ืฉื›ื•ืœื ื™ื”ื™ื• ืžืจื•ืฆื™ื ื›ืืŸ."
                ]
            elif part_name == "ื”ืžื’ืŸ":
                responses = [
                    f"ืื ื™ {display_name}, ื”ืžื’ืŸ ืฉืœืš. '{user_message}' - ืื ื™ ืžืขืจื™ืš ืืช ื”ืžืฆื‘. ื”ืื ื–ื” ื‘ื˜ื•ื—?",
                    f"ื–ื” {display_name}. ืฉืžืขืชื™ ืžื” ืฉืืžืจืช ืขืœ '{user_message}' ื•ืื ื™ ืžื™ื“ ื‘ื›ื•ื ื ื•ืช.",
                    f"ืื ื™ {display_name}, ื”ืฉื•ืžืจ ืฉืœืš. ืžื” ืฉืืžืจืช ืžืขื•ืจืจ ื‘ื™ ืืช ื”ืื™ื ืกื˜ื™ื ืงื˜ื™ื ื”ืžื’ื ื™ื™ื."
                ]
            elif part_name == "ื”ื ืžื ืข/ืช":
                responses = [
                    f"ืื ื™ {display_name}, ื”ื ืžื ืข/ืช ืฉืœืš. ืžื” ืฉืืžืจืช ืขืœ '{user_message}' ื’ื•ืจื ืœื™ ืœืจืฆื•ืช ืœื”ื™ืกื•ื’ ืงืฆืช.",
                    f"ื–ื” {display_name}. '{user_message}' - ื–ื” ื ืฉืžืข ืžื•ืจื›ื‘ ื•ืžืคื—ื™ื“. ื”ืื ื™ืฉ ื“ืจืš ืœื”ื™ืžื ืข ืžื–ื”?",
                    f"ืื ื™ {display_name}, ื•ืื ื™ ืžืจื’ื™ืฉ ืงืฆืช ื—ืจื“ื” ืž'{user_message}'."
                ]
            else:
                responses = [
                    f"ืื ื™ {display_name}, ื—ืœืง ืคื ื™ืžื™ ืฉืœืš. ืฉืžืขืชื™ ืืช '{user_message}' ื•ืื ื™ ื›ืืŸ ื›ื“ื™ ืœืฉื•ื—ื— ืื™ืชืš ืขืœ ื–ื”.",
                    f"ื–ื” {display_name}. ืžื” ืฉืืžืจืช ืžืขื ื™ื™ืŸ ืื•ืชื™. '{user_message}' - ื‘ื•ืื ื• ื ื—ืงื•ืจ ืืช ื–ื” ื™ื—ื“."
                ]
            
            selected_response = random.choice(responses)
            
            if user_context:
                selected_response += f" ื–ื›ื•ืจ ืฉืืžืจืช ื‘ื”ืชื—ืœื”: {user_context[:100]}..."
            
            return selected_response

        def create_session():
            return conv_manager.create_new_session()

        def set_context_and_part(user_context, part_choice, persona_name, state):
            state = conv_manager.set_initial_context(state, "general", user_context)
            state = conv_manager.set_selected_part(state, part_choice, persona_name, None, None)
            
            part_info = DEFAULT_PARTS.get(part_choice, {})
            display_name = persona_name if persona_name else part_info.get("default_persona_name", "ื—ืœืง ืคื ื™ืžื™")
            
            return state, f"๐Ÿ—ฃ๏ธ ื›ืขืช ืืชื” ืžืชืฉื•ื—ื— ืขื: **{display_name}** ({part_choice})"

        def chat_with_part(message, history, state):
            if not message.strip():
                return "", history, state
            
            if not state.selected_part:
                response = "ืื ื ื‘ื—ืจ ื—ืœืง ืคื ื™ืžื™ ืชื—ื™ืœื”"
            else:
                response = generate_persona_response(message, state.selected_part, state.persona_name, state.user_context)
                state = conv_manager.add_to_history(state, message, response)
            
            history.append([message, response])
            return "", history, state

        # Create simplified interface without API docs
        with gr.Blocks(title="ืžืจืื•ืช - ืžืจื—ื‘ ืื™ืฉื™ ืœืฉื™ื— ืคื ื™ืžื™", theme=gr.themes.Soft()) as demo:
            
            conversation_state = gr.State(create_session())
            
            gr.HTML("""
            <div style="text-align: center; margin-bottom: 30px;">
                <h1>๐Ÿชž ืžืจืื•ืช: ืžืจื—ื‘ ืื™ืฉื™ ืœืฉื™ื— ืคื ื™ืžื™</h1>
                <p>ืžืงื•ื ื‘ื˜ื•ื— ืœืฉื•ื—ื— ืขื ื”ื—ืœืงื™ื ื”ืฉื•ื ื™ื ืฉืœ ืขืฆืžืš</p>
                <div style="background-color: #e8f5e8; border: 1px solid #4caf50; padding: 10px; margin: 10px 0; border-radius: 5px;">
                    <strong>๐Ÿค– ืžืขืจื›ืช ืชื’ื•ื‘ื•ืช ืžื•ืชืืžืช ืื™ืฉื™ืช ืคืขื™ืœื”</strong>
                </div>
            </div>
            """)
            
            with gr.Row():
                with gr.Column():
                    user_context = gr.Textbox(
                        label="ืกืคืจ ืขืœ ืขืฆืžืš ืื• ืขืœ ื”ืžืฆื‘ ืฉืœืš:",
                        placeholder="ืœืžืฉืœ: ืื ื™ ืžืชืžื•ื“ื“ ืขื ืœื—ืฆื™ื ื‘ืขื‘ื•ื“ื”...",
                        lines=3
                    )
                    
                    part_choice = gr.Dropdown(
                        label="ื‘ื—ืจ ื—ืœืง ืคื ื™ืžื™ ืœืฉื™ื—ื”:",
                        choices=[
                            "ื”ืงื•ืœ ื”ื‘ื™ืงื•ืจืชื™",
                            "ื”ื™ืœื“/ื” ื”ืคื ื™ืžื™ืช", 
                            "ื”ืžืจืฆื”",
                            "ื”ืžื’ืŸ",
                            "ื”ื ืžื ืข/ืช"
                        ],
                        value="ื”ืงื•ืœ ื”ื‘ื™ืงื•ืจืชื™"
                    )
                    
                    persona_name = gr.Textbox(
                        label="ืฉื ืื™ืฉื™ ืœื—ืœืง (ืื•ืคืฆื™ื•ื ืœื™):",
                        placeholder="ืœืžืฉืœ: ื“ื ื”, ืขื“ืŸ, ื ื•ืขื”..."
                    )
                    
                    setup_btn = gr.Button("ื”ืชื—ืœ ืฉื™ื—ื”", variant="primary")
                    
                with gr.Column():
                    current_part = gr.Markdown("ื‘ื—ืจ ื”ื’ื“ืจื•ืช ื•ืœื—ืฅ ืขืœ 'ื”ืชื—ืœ ืฉื™ื—ื”'")
            
            # Chat interface
            with gr.Row():
                with gr.Column(scale=2):
                    chatbot = gr.Chatbot(height=400, label="ื”ืฉื™ื—ื” ืฉืœืš")
                    
                    with gr.Row():
                        msg_input = gr.Textbox(
                            label="ื”ื”ื•ื“ืขื” ืฉืœืš:",
                            placeholder="ื›ืชื•ื‘ ืืช ื”ืžื—ืฉื‘ื•ืช ืฉืœืš...",
                            lines=2,
                            scale=4
                        )
                        send_btn = gr.Button("ืฉืœื—", scale=1)
                    
                    clear_btn = gr.Button("ื ืงื” ืฉื™ื—ื”")
            
            # Event handlers
            setup_btn.click(
                fn=set_context_and_part,
                inputs=[user_context, part_choice, persona_name, conversation_state],
                outputs=[conversation_state, current_part]
            )
            
            msg_input.submit(
                fn=chat_with_part,
                inputs=[msg_input, chatbot, conversation_state],
                outputs=[msg_input, chatbot, conversation_state]
            )
            
            send_btn.click(
                fn=chat_with_part,
                inputs=[msg_input, chatbot, conversation_state],
                outputs=[msg_input, chatbot, conversation_state]
            )
            
            clear_btn.click(
                fn=lambda state: ([], conv_manager.clear_conversation(state)),
                inputs=[conversation_state],
                outputs=[chatbot, conversation_state]
            )

        # Launch with minimal configuration to avoid schema issues
        logger.info("๐Ÿš€ Launching simplified ืžืจืื•ืช app...")
        demo.launch(
            server_name="127.0.0.1",
            server_port=port,
            share=True,
            show_api=False,  # Disable API to prevent schema errors
            show_error=True,
            inbrowser=True,
            quiet=False
        )
        return True
        
    except Exception as e:
        logger.error(f"โŒ Simplified app failed: {e}")
        return False

def run_app():
    """Run the ืžืจืื•ืช application"""
    
    logger.info("๐Ÿชž Starting ืžืจืื•ืช application...")
    
    # Check dependencies
    if not check_dependencies():
        logger.error("Dependencies check failed. Exiting.")
        return False
    
    # Find available port
    port = find_available_port()
    logger.info(f"๐Ÿš€ Using port {port}")
    
    # Set environment variables for local development
    os.environ["GRADIO_SERVER_PORT"] = str(port)
    
    # Try simplified app first (more reliable)
    logger.info("๐ŸŽฏ Starting with simplified version for maximum reliability...")
    success = run_simple_app(port)
    
    if success:
        return True
    
    # If simplified app failed, try subprocess approach
    logger.info("๐Ÿ”„ Trying subprocess approach...")
    try:
        cmd = [sys.executable, "simple_app.py"]
        subprocess.run(cmd, check=True)
        return True
    except Exception as e:
        logger.error(f"โŒ Subprocess approach failed: {e}")
        return False

if __name__ == "__main__":
    print("๐Ÿชž ืžืจืื•ืช - Hebrew Self-Reflective AI Agent")
    print("=" * 50)
    
    success = run_app()
    
    if not success:
        print("\nโŒ Failed to start application")
        print("๐Ÿ“‹ Troubleshooting:")
        print("1. Make sure you're in a virtual environment")
        print("2. Install dependencies: pip install -r requirements.txt")
        print("3. Try running directly: python simple_app.py")
        print("4. Check Gradio version: pip install gradio==4.44.0")
        sys.exit(1)
    else:
        print("\nโœ… Application started successfully!")