shim5/mirrors
0
1# -*- coding: utf-8 -*-2"""3Simplified מראות (Mirrors) app for local testing4Uses the same template-based response system as the main app5"""6 7import os8# Force lightweight model for testing9os.environ["FORCE_LIGHT_MODEL"] = "1"10 11import gradio as gr12from conversation_manager import ConversationManager13from prompt_engineering import DEFAULT_PARTS14import random15 16# Initialize components17conv_manager = ConversationManager()18 19def generate_persona_response(user_message: str, part_name: str, persona_name: str, user_context: str = None, conversation_history=None):20 """21 Generate persona-based response using templates22 Same system as the main app23 """24 part_info = DEFAULT_PARTS.get(part_name, {})25 display_name = persona_name or part_info.get("default_persona_name", "חלק פנימי")26 27 # Generate contextual responses based on part type28 if part_name == "הקול הביקורתי":29 responses = [30 f"אני {display_name}, הקול הביקורתי שלך. שמעתי מה שאמרת על '{user_message}' - אני חושב שצריך לבחון את זה יותר לעומק. מה באמת עומד מאחורי המחשבות האלה?",31 f"אני {display_name}. מה שאמרת מעורר בי שאלות. '{user_message}' - אבל האם זה באמת המצב המלא? אולי יש כאן דברים שאתה לא רואה?",32 f"זה {display_name} מדבר. אני שומע אותך אומר '{user_message}', אבל אני מרגיש שאנחנו צריכים להיות יותר ביקורתיים כאן. מה אתה לא מספר לעצמך?",33 f"אני {display_name}, ואני כאן כדי לעזור לך לראות את התמונה המלאה. מה שאמרת על '{user_message}' - זה רק חצי מהסיפור, לא? בואנו נחפור עמוק יותר."34 ]35 36 elif part_name == "הילד/ה הפנימית":37 responses = [38 f"אני {display_name}, הילד/ה הפנימית שלך. מה שאמרת על '{user_message}' גורם לי להרגיש... קצת פגיע. אתה באמת שומע אותי עכשיו?",39 f"זה {display_name}. '{user_message}' - זה מבהיל אותי קצת. אני צריך לדעת שהכל יהיה בסדר. אתה יכול להרגיע אותי?",40 f"אני {display_name}, החלק הצעיר שלך. מה שאמרת נוגע ללב שלי. '{user_message}' - אני מרגיש שיש כאן משהו חשוב שאני צריך להבין.",41 f"זה {display_name} מדבר בשקט. אני שומע את '{user_message}' וזה מעורר בי רגשות. האם זה בטוח לחשוב על זה? אני קצת חרד."42 ]43 44 elif part_name == "המרצה":45 responses = [46 f"אני {display_name}, המרצה שלך. שמעתי את '{user_message}' ואני רוצה לוודא שכולם יהיו בסדר עם זה. איך אנחנו יכולים לפתור את זה בצורה שתרצה את כולם?",47 f"זה {display_name}. מה שאמרת על '{user_message}' גורם לי לדאוג - האם זה יכול לפגוע במישהו? בואנו נמצא דרך עדינה יותר להתמודד עם זה.",48 f"אני {display_name}, ואני רוצה שכולם יהיו מרוצים כאן. '{user_message}' - זה נשמע כמו משהו שיכול ליצור מתח. איך נוכל לעשות את זה בצורה שכולם יאהבו?",49 f"זה {display_name} מדבר. אני שומע את '{user_message}' ומיד אני חושב - מה אחרים יגידו על זה? בואנו נוודא שאנחנו לא פוגעים באף אחד."50 ]51 52 elif part_name == "המגן":53 responses = [54 f"אני {display_name}, המגן שלך. '{user_message}' - אני מעריך את המצב. האם זה בטוח? אני כאן כדי לשמור עליך מכל מה שיכול לפגוע בך.",55 f"זה {display_name}. שמעתי מה שאמרת על '{user_message}' ואני מיד בכוננות. מה האיומים כאן? איך אני יכול להגן עליך טוב יותר?",56 f"אני {display_name}, השומר שלך. מה שאמרת מעורר בי את האינסטינקטים המגניים. '{user_message}' - בואנו נוודא שאתה חזק מספיק להתמודד עם זה.",57 f"זה {display_name} מדבר. אני שומע את '{user_message}' ואני חושב על אסטרטגיות הגנה. מה אנחנו צריכים לעשות כדי שתהיה בטוח?"58 ]59 60 elif part_name == "הנמנע/ת":61 responses = [62 f"אני {display_name}, הנמנע/ת שלך. מה שאמרת על '{user_message}' גורם לי לרצות להיסוג קצת. אולי... לא חייבים להתמודד עם זה עכשיו?",63 f"זה {display_name}. '{user_message}' - זה נשמע מורכב ומפחיד. האם יש דרך להימנע מזה? לפעמים עדיף לא להיכנס למצבים קשים.",64 f"אני {display_name}, ואני מרגיש קצת חרדה מ'{user_message}'. בואנו נחזור לזה אחר כך? אולי עכשיו זה לא הזמן המתאים.",65 f"זה {display_name} מדבר בזהירות. מה שאמרת מעורר בי רצון לברוח. '{user_message}' - האם באמת צריך להתמודד עם זה עכשיו?"66 ]67 68 else:69 responses = [70 f"אני {display_name}, חלק פנימי שלך. שמעתי את '{user_message}' ואני כאן כדי לשוחח איתך על זה. מה עוד אתה מרגיש לגבי המצב הזה?",71 f"זה {display_name}. מה שאמרת מעניין אותי. '{user_message}' - בואנו נחקור את זה יחד ונבין מה זה אומר עליך.",72 f"אני {display_name}, ואני רוצה להבין אותך טוב יותר. '{user_message}' - איך זה משפיע עליך ברמה הרגשית?",73 f"זה {display_name} מדבר. אני שומע את '{user_message}' ואני סקרן לדעת יותר. מה עוד יש בך בנושא הזה?"74 ]75 76 # Select response based on context or randomly77 if "פחד" in user_message or "חרדה" in user_message:78 selected_response = responses[1] if len(responses) > 1 else responses[0]79 elif "כעס" in user_message or "מרגיש רע" in user_message:80 selected_response = responses[2] if len(responses) > 2 else responses[0]81 else:82 selected_response = random.choice(responses)83 84 # Add user context if relevant85 if user_context and len(conversation_history or []) < 4:86 selected_response += f" זכור שאמרת בהתחלה: {user_context[:100]}..."87 88 return selected_response89 90def create_session():91 """Create a new conversation session"""92 return conv_manager.create_new_session()93 94def set_context_and_part(user_context, part_choice, persona_name, state):95 """Set user context and selected part"""96 # Set initial context97 state = conv_manager.set_initial_context(state, "general", user_context)98 99 # Set selected part100 state = conv_manager.set_selected_part(state, part_choice, persona_name, None, None)101 102 part_info = DEFAULT_PARTS.get(part_choice, {})103 display_name = persona_name if persona_name else part_info.get("default_persona_name", "חלק פנימי")104 105 return state, f"🗣️ כעת אתה מתשוחח עם: **{display_name}** ({part_choice})"106 107def chat_with_part(message, history, state):108 """Generate response from selected part"""109 if not message.strip():110 return "", history, state111 112 if not state.selected_part:113 response = "אנא בחר חלק פנימי תחילה"114 else:115 response = generate_persona_response(116 message, 117 state.selected_part, 118 state.persona_name,119 state.user_context,120 state.conversation_history121 )122 state = conv_manager.add_to_history(state, message, response)123 124 history.append([message, response])125 return "", history, state126 127# Create simplified interface128with gr.Blocks(title="מראות - מרחב אישי לשיח פנימי", theme=gr.themes.Soft()) as demo:129 130 # Session state131 conversation_state = gr.State(create_session())132 133 gr.HTML("""134 <div style="text-align: center; margin-bottom: 30px;">135 <h1>🪞 מראות: מרחב אישי לשיח פנימי</h1>136 <p>מקום בטוח לשוחח עם החלקים השונים של עצמך</p>137 <div style="background-color: #e8f5e8; border: 1px solid #4caf50; padding: 10px; margin: 10px 0; border-radius: 5px;">138 <strong>🤖 מערכת תגובות מותאמת אישית פעילה</strong>139 </div>140 </div>141 """)142 143 with gr.Row():144 with gr.Column():145 user_context = gr.Textbox(146 label="ספר על עצמך או על המצב שלך:",147 placeholder="למשל: אני מתמודד עם לחצים בעבודה...",148 lines=3149 )150 151 part_choice = gr.Dropdown(152 label="בחר חלק פנימי לשיחה:",153 choices=[154 "הקול הביקורתי",155 "הילד/ה הפנימית", 156 "המרצה",157 "המגן",158 "הנמנע/ת"159 ],160 value="הקול הביקורתי"161 )162 163 persona_name = gr.Textbox(164 label="שם אישי לחלק (אופציונלי):",165 placeholder="למשל: דנה, עדן, נועה..."166 )167 168 setup_btn = gr.Button("התחל שיחה", variant="primary")169 170 with gr.Column():171 current_part = gr.Markdown("בחר הגדרות ולחץ על 'התחל שיחה'")172 173 # Chat interface174 with gr.Row():175 with gr.Column(scale=2):176 chatbot = gr.Chatbot(height=400, label="השיחה שלך", rtl=True)177 178 with gr.Row():179 msg_input = gr.Textbox(180 label="ההודעה שלך:",181 placeholder="כתוב את המחשבות שלך...",182 lines=2,183 scale=4184 )185 send_btn = gr.Button("שלח", scale=1)186 187 clear_btn = gr.Button("נקה שיחה")188 189 # Event handlers190 setup_btn.click(191 fn=set_context_and_part,192 inputs=[user_context, part_choice, persona_name, conversation_state],193 outputs=[conversation_state, current_part]194 )195 196 msg_input.submit(197 fn=chat_with_part,198 inputs=[msg_input, chatbot, conversation_state],199 outputs=[msg_input, chatbot, conversation_state]200 )201 202 send_btn.click(203 fn=chat_with_part,204 inputs=[msg_input, chatbot, conversation_state],205 outputs=[msg_input, chatbot, conversation_state]206 )207 208 clear_btn.click(209 fn=lambda state: ([], conv_manager.clear_conversation(state)),210 inputs=[conversation_state],211 outputs=[chatbot, conversation_state]212 )213 214if __name__ == "__main__":215 print("🧪 Starting simplified מראות app...")216 # Find available port217 import socket218 for port in range(7864, 7874):219 try:220 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:221 s.bind(('127.0.0.1', port))222 available_port = port223 break224 except OSError:225 continue226 else:227 available_port = 7864228 229 print(f"🚀 Starting on port {available_port}")230 demo.launch(231 server_name="127.0.0.1",232 server_port=available_port,233 share=True,234 show_api=False,235 debug=False,236 inbrowser=True237 ) 