Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596import gradio as grfrom self_learning_bot import UnrestrictedChatbotimport os# Initialize bot with persistent storagestate_path = "/tmp/chatbot_state.json"bot = UnrestrictedChatbot(state_file=state_path)def respond(message, history):bot.learn_from_feedback("", 1.0) # Learn from successful responses# Get bot responseresponse = bot.chat(message)# Show learning statsstats = bot.get_learning_stats()learning_info = f"π€ Patterns: {stats['patterns']} | Memory: {stats['memory_size']} | Score: {stats['avg_score']:.2f}"if history is None:history = []history.append((message, f"{response}\n\n{learning_info}"))return history, historydef add_feedback(feedback, history):if feedback and history:# Learn from user feedback (1-5 scale)try:score = float(feedback)if 1 <= score <= 5:bot.learn_from_feedback(history[-1][0], score / 5.0) # Convert to 0-1 scalereturn f"β Learned from feedback: {score}/5"except:passreturn "β Please enter a number 1-5"with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("""# π Phoenix AI (Real Self-Learning Chatbot)*This bot actually learns from every conversation and improves over time!*""")chatbot = gr.Chatbot(height=400, label="Learning Chat")state = gr.State([])with gr.Row():msg = gr.Textbox(label="Your message",placeholder="Type anything... the bot learns from your conversations!",scale=4)send_btn = gr.Button("Send", scale=1)with gr.Row():feedback = gr.Textbox(label="Rate last response (1-5)",placeholder="Help me learn! Rate 1(bad) to 5(great)",scale=3)learn_btn = gr.Button("Submit Feedback", scale=1)reset_btn = gr.Button("Reset Chat", scale=1)learning_stats = gr.Textbox(label="Learning Statistics",interactive=False,value="Bot will show learning progress here...")# Update statsdef update_stats():stats = bot.get_learning_stats()return f"π Learned Patterns: {stats['patterns']} | Conversations: {stats['memory_size']} | Avg Score: {stats['avg_score']:.2f} | Recent Rewards: {stats['recent_rewards']}"# Main interactionsdef user_message(message, history):if not message.strip():return "", historynew_history = respond(message, history or [])return "", new_history[0], update_stats()msg.submit(user_message, [msg, state], [msg, chatbot, learning_stats])send_btn.click(user_message, [msg, state], [msg, chatbot, learning_stats])learn_btn.click(add_feedback,[feedback, chatbot],[feedback]).then(update_stats, None, [learning_stats])reset_btn.click(lambda: ([], [], "Chat reset!"),None,[chatbot, state, learning_stats])if __name__ == "__main__":demo.launch(show_error=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106import gradio as grfrom self_learning_bot import EnhancedLearningBotimport osimport time# Initialize the enhanced botbot = EnhancedLearningBot()def respond(message, history, enable_search):# Get response with optional web searchresponse, search_context = bot.chat(message,use_web_search=enable_search,conversation_history=history)# Learn from this interactionbot.learn_from_interaction(message, response, search_context)# Display learning stats and search infostats = bot.get_learning_stats()search_info = "π Web Search Used" if search_context else "π From Memory"learning_info = f"{search_info} | Patterns: {stats['patterns']} | Score: {stats['avg_score']:.2f}"if history is None:history = []full_response = f"{response}\n\n{learning_info}"history.append((message, full_response))return history, historydef add_feedback(feedback, history):if feedback and history:try:score = float(feedback)if 1 <= score <= 5:bot.learn_from_feedback(history[-1][0], score / 5.0)return f"β Learned from feedback: {score}/5"except:passreturn "β Please enter 1-5"with gr.Blocks(theme=gr.themes.Soft(), title="Phoenix AI - Web Enhanced") as demo:gr.Markdown("""# π Phoenix AI - Web Enhanced**Now with real-time web search and continuous learning!**""")chatbot = gr.Chatbot(height=400, label="Learning Chat")state = gr.State([])with gr.Row():with gr.Column(scale=4):msg = gr.Textbox(label="Your message",placeholder="Ask me anything... I can search the web for latest information!",container=False)with gr.Column(scale=1):search_toggle = gr.Checkbox(label="π Enable Web Search", value=True)send_btn = gr.Button("Send", variant="primary")with gr.Row():feedback = gr.Textbox(label="Rate last response (1-5)",placeholder="Help me learn! Rate 1-5",scale=3)learn_btn = gr.Button("Submit Feedback", scale=1)clear_btn = gr.Button("Clear Chat", scale=1)learning_stats = gr.Textbox(label="Learning Statistics",value="Ready to learn and search...",interactive=False)# Update stats displaydef update_stats():stats = bot.get_learning_stats()return f"π Learned: {stats['patterns']} patterns | Memory: {stats['memory_size']} | Recent Success: {stats['recent_rewards']}/10"# Main interaction flowdef user_message(message, history, search_toggle):if not message.strip():return "", historynew_history = respond(message, history or [], search_toggle)return "", new_history[0], update_stats()# Event handlersmsg.submit(user_message, [msg, state, search_toggle], [msg, chatbot, learning_stats])send_btn.click(user_message, [msg, state, search_toggle], [msg, chatbot, learning_stats])learn_btn.click(add_feedback,[feedback, chatbot],[feedback]).then(update_stats, None, [learning_stats])clear_btn.click(lambda: ([], [], "Chat cleared!"),None,[chatbot, state, learning_stats])if __name__ == "__main__":demo.launch(share=True, show_error=True)
app.py+50-40