DreamStream-1 commited on
Commit
025f913
Β·
verified Β·
1 Parent(s): 33e434f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +3 -288
app.py CHANGED
@@ -42,7 +42,6 @@ from difflib import SequenceMatcher
42
  import httpx
43
  import langdetect
44
  from langdetect import detect
45
- import gradio as gr
46
  import threading
47
 
48
  # Configure advanced logging
@@ -2808,291 +2807,7 @@ Response:
2808
  error_msg = "❌ AI Assistant encountered an error. Please try again or type 'main' to return to main menu."
2809
  send_whatsjet_message(from_number, error_msg)
2810
 
2811
- # ============================================================================
2812
- # GRADIO INTERFACE FUNCTIONS
2813
- # ============================================================================
2814
-
2815
- # Global variables for Gradio
2816
- bot_status = "Running" # Bot is running since it's integrated
2817
- bot_thread = None
2818
-
2819
- def get_bot_status():
2820
- """Get the current status of the bot"""
2821
- global bot_status
2822
- try:
2823
- # Try to connect to the bot's health endpoint
2824
- response = requests.get("http://localhost:7860/health", timeout=5)
2825
- if response.status_code == 200:
2826
- data = response.json()
2827
- if data.get("status") == "healthy":
2828
- bot_status = "Running"
2829
- return "🟒 Running", data
2830
- else:
2831
- bot_status = "Error"
2832
- return "πŸ”΄ Error", data
2833
- else:
2834
- bot_status = "Error"
2835
- return "πŸ”΄ Error", {"error": f"HTTP {response.status_code}"}
2836
- except Exception as e:
2837
- bot_status = "Stopped"
2838
- return "πŸ”΄ Stopped", {"error": str(e)}
2839
-
2840
- def start_bot():
2841
- """Start the WhatsApp bot (for Gradio interface)"""
2842
- global bot_status
2843
-
2844
- if bot_status == "Running":
2845
- return "Bot is already running!", "🟒 Running", "Bot is already active"
2846
-
2847
- try:
2848
- bot_status = "Running"
2849
- return "βœ… Bot started successfully!", "🟒 Running", "Bot is now running on port 7860"
2850
- except Exception as e:
2851
- return f"❌ Error starting bot: {str(e)}", "πŸ”΄ Stopped", f"Error: {str(e)}"
2852
-
2853
- def stop_bot():
2854
- """Stop the WhatsApp bot (for Gradio interface)"""
2855
- global bot_status
2856
-
2857
- try:
2858
- bot_status = "Stopped"
2859
- return "βœ… Bot stopped successfully!", "πŸ”΄ Stopped", "Bot has been stopped"
2860
- except:
2861
- bot_status = "Stopped"
2862
- return "βœ… Bot stopped!", "πŸ”΄ Stopped", "Bot has been stopped"
2863
-
2864
- def get_health_info():
2865
- """Get detailed health information"""
2866
- try:
2867
- response = requests.get("http://localhost:7860/health", timeout=5)
2868
- if response.status_code == 200:
2869
- data = response.json()
2870
- return f"""
2871
- ## πŸ₯ Bot Health Status
2872
-
2873
- **Status**: {data.get('status', 'Unknown')}
2874
- **Timestamp**: {data.get('timestamp', 'Unknown')}
2875
- **Products Loaded**: {'βœ… Yes' if data.get('products_loaded') else '❌ No'}
2876
- **OpenAI Available**: {'βœ… Yes' if data.get('openai_available') else '❌ No'}
2877
- **WhatsJet Configured**: {'βœ… Yes' if data.get('whatsjet_configured') else '❌ No'}
2878
-
2879
- **Environment**: Hugging Face Spaces
2880
- **Port**: 7860
2881
- **Version**: 2.0.0 (Complete Edition)
2882
- """
2883
- else:
2884
- return "❌ Unable to get health information"
2885
- except Exception as e:
2886
- return f"❌ Error getting health info: {str(e)}"
2887
-
2888
- def get_webhook_info():
2889
- """Get webhook configuration information"""
2890
- server_url = os.getenv("SERVER_URL", "Not configured")
2891
- whatsjet_url = os.getenv("WHATSJET_API_URL", "Not configured")
2892
- vendor_uid = os.getenv("WHATSJET_VENDOR_UID", "Not configured")
2893
-
2894
- return f"""
2895
- ## πŸ”— Webhook Configuration
2896
-
2897
- **Server URL**: {server_url}
2898
- **WhatsJet API URL**: {whatsjet_url}
2899
- **Vendor UID**: {vendor_uid[:10] + '...' if len(vendor_uid) > 10 else vendor_uid}
2900
- **Webhook Endpoint**: {server_url}/webhook
2901
-
2902
- ## πŸ“‹ Setup Instructions
2903
-
2904
- 1. **Configure WhatsJet Dashboard**:
2905
- - Log into your WhatsJet dashboard
2906
- - Go to webhook settings
2907
- - Set webhook URL to: `{server_url}/webhook`
2908
- - Enable webhook
2909
-
2910
- 2. **Test Webhook**:
2911
- ```bash
2912
- curl -X POST {server_url}/webhook \\
2913
- -H "Content-Type: application/json" \\
2914
- -d '{{"test": "message"}}'
2915
- ```
2916
-
2917
- 3. **Health Check**:
2918
- ```bash
2919
- curl {server_url}/health
2920
- ```
2921
-
2922
- 4. **Voice Test**:
2923
- ```bash
2924
- curl {server_url}/test-voice
2925
- ```
2926
- """
2927
-
2928
- def get_product_info():
2929
- """Get information about the product database"""
2930
- try:
2931
- if products_df is not None and not products_df.empty:
2932
- categories = products_df['Category'].value_counts().to_dict()
2933
- total_products = len(products_df)
2934
-
2935
- category_info = "\n".join([f"- **{cat}**: {count} products" for cat, count in categories.items()])
2936
-
2937
- return f"""
2938
- ## πŸ“¦ Product Database
2939
-
2940
- **Total Products**: {total_products}
2941
-
2942
- **Categories**:
2943
- {category_info}
2944
-
2945
- **Sample Products**:
2946
- {products_df.head(5)[['Product Name', 'Category']].to_string(index=False)}
2947
- """
2948
- else:
2949
- return "❌ No products loaded"
2950
- except Exception as e:
2951
- return f"❌ Error reading product database: {str(e)}"
2952
-
2953
- def get_bot_features():
2954
- """Get information about bot features"""
2955
- return """
2956
- ## 🎯 Bot Features (Complete Edition)
2957
-
2958
- ### πŸ€– AI & Intelligence
2959
- - **GPT-4 Integration** - Advanced AI responses
2960
- - **Voice Transcription** - OpenAI Whisper support
2961
- - **Language Detection** - Auto-detect English/Urdu
2962
- - **Smart Context Management** - Remember user preferences
2963
- - **Intelligent Product Matching** - Fuzzy search with veterinary domain knowledge
2964
-
2965
- ### πŸ₯ Veterinary Features
2966
- - **Product Catalog** - 25+ veterinary products
2967
- - **Category Browsing** - Organized by treatment type
2968
- - **PDF Generation** - Dynamic catalogs and product sheets
2969
- - **Symptom Matching** - Intelligent product recommendations
2970
- - **Species-Specific Advice** - Poultry, livestock, pets
2971
-
2972
- ### πŸ“± WhatsApp Integration
2973
- - **Webhook Handling** - Real-time message processing
2974
- - **Voice Messages** - Audio transcription and response
2975
- - **Menu System** - Context-aware navigation
2976
- - **Contact Management** - Inquiries and availability requests
2977
- - **Analytics** - User interaction tracking
2978
-
2979
- ### 🌍 Multilingual Support
2980
- - **English** - Primary language
2981
- - **Urdu** - Full translation support
2982
- - **Auto-Detection** - Language switching
2983
- - **Cultural Adaptation** - Localized responses
2984
-
2985
- ### πŸ“Š Advanced Features
2986
- - **Conversation History** - Persistent user sessions
2987
- - **Product Analytics** - Usage tracking
2988
- - **Error Handling** - Graceful failure recovery
2989
- - **Logging** - Comprehensive activity logs
2990
- - **Health Monitoring** - System status checks
2991
- """
2992
-
2993
- # ============================================================================
2994
- # GRADIO INTERFACE
2995
- # ============================================================================
2996
-
2997
- # Create Gradio interface
2998
- with gr.Blocks(title="Apex Biotical Veterinary WhatsApp Bot - Complete Edition", theme=gr.themes.Soft(), app=app) as demo:
2999
- gr.Markdown("""
3000
- # πŸ₯ Apex Biotical Veterinary WhatsApp Bot - Complete Edition
3001
-
3002
- **The most effective and accurate veterinary chatbot in the market**
3003
-
3004
- *3000+ lines of advanced veterinary AI with comprehensive features*
3005
-
3006
- ---
3007
- """)
3008
-
3009
- with gr.Row():
3010
- with gr.Column(scale=1):
3011
- gr.Markdown("### πŸš€ Bot Control")
3012
-
3013
- status_display = gr.Textbox(
3014
- label="Bot Status",
3015
- value="🟒 Running",
3016
- interactive=False
3017
- )
3018
-
3019
- with gr.Row():
3020
- start_btn = gr.Button("▢️ Start Bot", variant="primary", size="lg")
3021
- stop_btn = gr.Button("⏹️ Stop Bot", variant="secondary", size="lg")
3022
-
3023
- status_output = gr.Textbox(
3024
- label="Status Message",
3025
- interactive=False
3026
- )
3027
-
3028
- gr.Markdown("### πŸ“Š Quick Actions")
3029
- refresh_btn = gr.Button("πŸ”„ Refresh Status", size="lg")
3030
-
3031
- with gr.Column(scale=2):
3032
- gr.Markdown("### πŸ“ˆ System Information")
3033
- health_info = gr.Markdown("Click 'Refresh Status' to see bot information")
3034
-
3035
- with gr.Tabs():
3036
- with gr.TabItem("πŸ₯ Health Status"):
3037
- health_tab = gr.Markdown("Click 'Refresh Status' to see detailed health information")
3038
-
3039
- with gr.TabItem("πŸ”— Webhook Setup"):
3040
- webhook_tab = gr.Markdown("Click 'Refresh Status' to see webhook configuration")
3041
-
3042
- with gr.TabItem("πŸ“¦ Products"):
3043
- products_tab = gr.Markdown("Click 'Refresh Status' to see product database information")
3044
-
3045
- with gr.TabItem("🎯 Features"):
3046
- features_tab = gr.Markdown(get_bot_features())
3047
-
3048
- gr.Markdown("""
3049
- ---
3050
-
3051
- ## πŸ”§ Environment Variables Required
3052
-
3053
- Make sure these are set in your Hugging Face Space secrets:
3054
-
3055
- - `WHATSJET_API_URL` - WhatsJet API endpoint
3056
- - `WHATSJET_VENDOR_UID` - Your vendor UID
3057
- - `WHATSJET_API_TOKEN` - Your API token
3058
- - `OPENAI_API_KEY` - OpenAI API key for AI features
3059
- - `SERVER_URL` - Your Hugging Face Space URL
3060
-
3061
- ## πŸ“ž Support
3062
-
3063
- - Check logs in your Hugging Face Space dashboard
3064
- - Monitor the health endpoint at `/health`
3065
- - Test webhook functionality
3066
- - Contact support if needed
3067
-
3068
- ## πŸŽ‰ Ready to Deploy!
3069
-
3070
- This is the complete 3000-line veterinary bot with all advanced features!
3071
- """)
3072
-
3073
- # Event handlers
3074
- start_btn.click(
3075
- fn=start_bot,
3076
- outputs=[status_output, status_display, health_info]
3077
- )
3078
-
3079
- stop_btn.click(
3080
- fn=stop_bot,
3081
- outputs=[status_output, status_display, health_info]
3082
- )
3083
-
3084
- def refresh_all():
3085
- status, data = get_bot_status()
3086
- health = get_health_info()
3087
- webhook = get_webhook_info()
3088
- products = get_product_info()
3089
- return status, health, webhook, products
3090
-
3091
- refresh_btn.click(
3092
- fn=refresh_all,
3093
- outputs=[health_tab, health_tab, webhook_tab, products_tab]
3094
- )
3095
-
3096
  if __name__ == "__main__":
3097
- # Launch Gradio interface (which includes the FastAPI app)
3098
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
42
  import httpx
43
  import langdetect
44
  from langdetect import detect
 
45
  import threading
46
 
47
  # Configure advanced logging
 
2807
  error_msg = "❌ AI Assistant encountered an error. Please try again or type 'main' to return to main menu."
2808
  send_whatsjet_message(from_number, error_msg)
2809
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2810
  if __name__ == "__main__":
2811
+ # Launch FastAPI app
2812
+ import uvicorn
2813
+ uvicorn.run(app, host="0.0.0.0", port=7860)