petter2025 commited on
Commit
804a1ea
Β·
verified Β·
1 Parent(s): 6dc71ce

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -45
app.py CHANGED
@@ -346,6 +346,15 @@ class Settings:
346
  self.architectural_honesty = True
347
  self.engineer_annual_cost = 200000
348
  self.default_savings_rate = 0.25 # FIXED: Added missing attribute
 
 
 
 
 
 
 
 
 
349
 
350
  settings = Settings()
351
 
@@ -3003,43 +3012,33 @@ def main():
3003
  print("🎨 MODERN UI: Design system with responsive components")
3004
  print("="*60 + "\n")
3005
 
3006
- # ============ FIXED: PORT HANDLING FOR HUGGING FACE SPACES ============
3007
- # Get port from environment variable or use a dynamic port finder
3008
- port = 7860 # Default
3009
 
3010
- # Try to find a free port if default is in use
3011
- try:
3012
- import socket
3013
- sock = socket.socket()
3014
- sock.bind(('', 0))
3015
- port = sock.getsockname()[1]
3016
- sock.close()
3017
- logger.info(f"βœ… Found free port: {port}")
3018
- except Exception as e:
3019
- logger.warning(f"⚠️ Could not find free port, using default: {e}")
3020
-
3021
- # Launch configuration - FIXED: Use dynamic port
3022
- launch_config = {
3023
- "server_name": "0.0.0.0",
3024
- "server_port": port,
3025
- "share": False,
3026
- "favicon_path": None,
3027
- "quiet": False,
3028
- "show_error": True,
3029
- "debug": False,
3030
- "max_threads": 40,
3031
- }
3032
 
3033
- # Add CSS if available
3034
- css_styles = load_css_files()
3035
- if css_styles:
3036
- launch_config["css"] = css_styles
3037
 
3038
- logger.info(f"βœ… Launching demo on port {port} with config: {launch_config}")
3039
- print(f"🌐 Starting on http://localhost:{port}")
3040
 
3041
- # LAUNCH THE DEMO - THIS IS THE CRITICAL PART
3042
- demo.launch(**launch_config)
 
 
 
 
 
 
 
 
 
 
3043
 
3044
  except KeyboardInterrupt:
3045
  logger.info("πŸ‘‹ Demo stopped by user")
@@ -3049,7 +3048,6 @@ def main():
3049
  print("Please check the logs for more details.")
3050
  sys.exit(1)
3051
 
3052
-
3053
  # ===========================================
3054
  # HUGGING FACE SPACES COMPATIBILITY
3055
  # ===========================================
@@ -3059,10 +3057,39 @@ if __name__ == "__main__":
3059
  # For Hugging Face Spaces, we need to ensure the app stays alive
3060
  import os
3061
 
3062
- # Set environment variables for better compatibility
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3063
  os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
3064
- os.environ["GRADIO_SERVER_PORT"] = "7860" # Set default, but main() will find free port
3065
  os.environ["GRADIO_SERVER_NAME"] = "0.0.0.0"
 
 
 
 
 
 
3066
 
3067
  print("\n" + "="*60)
3068
  print("πŸš€ ARF Demo Starting on Hugging Face Spaces")
@@ -3070,7 +3097,13 @@ if __name__ == "__main__":
3070
  print(f"πŸ“Š Python version: {sys.version}")
3071
  print("="*60 + "\n")
3072
 
3073
- # Check for required files
 
 
 
 
 
 
3074
  required_files = ["styles/modern.css", "styles/responsive.css", "ui/components.py"]
3075
  missing_files = []
3076
 
@@ -3082,15 +3115,59 @@ if __name__ == "__main__":
3082
  if missing_files:
3083
  print(f"⚠️ Missing {len(missing_files)} required files")
3084
  print("⚠️ Some features may not work correctly")
 
 
 
 
 
 
 
 
 
 
 
 
 
3085
 
3086
- # Fix for uvicorn compatibility issue
3087
  try:
3088
- # Apply nest_asyncio before any async operations
3089
- import nest_asyncio
3090
- nest_asyncio.apply()
3091
- logger.info("βœ… Applied nest_asyncio for Hugging Face Spaces compatibility")
3092
  except Exception as e:
3093
- logger.warning(f"⚠️ Could not apply nest_asyncio: {e}")
 
 
3094
 
3095
- # Start the main application
3096
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
  self.architectural_honesty = True
347
  self.engineer_annual_cost = 200000
348
  self.default_savings_rate = 0.25 # FIXED: Added missing attribute
349
+ self.cache_miss_impact = 8500
350
+ self.database_impact = 4200
351
+ self.kubernetes_impact = 5500
352
+ self.api_impact = 3800
353
+ self.network_impact = 12000
354
+ self.storage_impact = 6800
355
+ self.telemetry_enabled = True
356
+ self.mcp_mode = "simulated"
357
+ self.enterprise_features = ["simulated_execution", "rollback_guarantee"]
358
 
359
  settings = Settings()
360
 
 
3012
  print("🎨 MODERN UI: Design system with responsive components")
3013
  print("="*60 + "\n")
3014
 
3015
+ # ============ HUGGING FACE SPACES SPECIFIC ============
3016
+ # Spaces handles ports differently - use their system
3017
+ import os
3018
 
3019
+ # Get port from environment (Spaces sets this)
3020
+ port = int(os.getenv("GRADIO_SERVER_PORT", "7860"))
3021
+ server_name = os.getenv("GRADIO_SERVER_NAME", "0.0.0.0")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3022
 
3023
+ # CRITICAL: For Spaces, Gradio needs to try multiple ports
3024
+ # Use a port range instead of a single port
3025
+ server_ports = [port, port + 1, port + 2] # Try multiple ports
 
3026
 
3027
+ # Get CSS if available
3028
+ css_styles = load_css_files()
3029
 
3030
+ logger.info(f"πŸš€ Launching on {server_name} with ports: {server_ports}")
3031
+ print(f"🌐 Starting on http://{server_name}:{port}")
3032
+
3033
+ # SIMPLE LAUNCH FOR SPACES COMPATIBILITY
3034
+ demo.launch(
3035
+ server_name=server_name,
3036
+ server_port=port,
3037
+ share=False,
3038
+ debug=False,
3039
+ show_error=True,
3040
+ quiet=True # Reduce log noise
3041
+ )
3042
 
3043
  except KeyboardInterrupt:
3044
  logger.info("πŸ‘‹ Demo stopped by user")
 
3048
  print("Please check the logs for more details.")
3049
  sys.exit(1)
3050
 
 
3051
  # ===========================================
3052
  # HUGGING FACE SPACES COMPATIBILITY
3053
  # ===========================================
 
3057
  # For Hugging Face Spaces, we need to ensure the app stays alive
3058
  import os
3059
 
3060
+ # ============ CRITICAL FIXES FOR HUGGING FACE SPACES ============
3061
+
3062
+ # 1. Fix uvicorn/nest_asyncio compatibility issue FIRST
3063
+ # This must happen before ANY asyncio operations
3064
+ try:
3065
+ import nest_asyncio
3066
+ import asyncio
3067
+
3068
+ # Get or create event loop
3069
+ try:
3070
+ loop = asyncio.get_event_loop()
3071
+ except RuntimeError:
3072
+ # No event loop exists yet, create one
3073
+ loop = asyncio.new_event_loop()
3074
+ asyncio.set_event_loop(loop)
3075
+
3076
+ # Apply nest_asyncio to the event loop
3077
+ nest_asyncio.apply(loop)
3078
+ logger.info("βœ… Applied nest_asyncio to event loop - fixes uvicorn loop_factory error")
3079
+ except Exception as e:
3080
+ logger.warning(f"⚠️ Could not apply nest_asyncio: {e}")
3081
+ # Continue anyway - some versions might work without it
3082
+
3083
+ # 2. Set environment variables for Hugging Face Spaces compatibility
3084
  os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
3085
+ os.environ["GRADIO_SERVER_PORT"] = "7860" # Spaces will override this if needed
3086
  os.environ["GRADIO_SERVER_NAME"] = "0.0.0.0"
3087
+ os.environ["GRADIO_HOT_RELOAD"] = "False" # Disable hot reload in Spaces
3088
+ os.environ["GRADIO_QUEUE_ENABLED"] = "True" # Enable queue for stability
3089
+
3090
+ # 3. Additional fixes for uvicorn warnings
3091
+ os.environ["UVICORN_LOG_LEVEL"] = "warning" # Reduce uvicorn log noise
3092
+ os.environ["UVICORN_ACCESS_LOG"] = "False" # Disable access logs
3093
 
3094
  print("\n" + "="*60)
3095
  print("πŸš€ ARF Demo Starting on Hugging Face Spaces")
 
3097
  print(f"πŸ“Š Python version: {sys.version}")
3098
  print("="*60 + "\n")
3099
 
3100
+ # 4. Detect if we're running in Hugging Face Spaces
3101
+ is_huggingface_space = "SPACE_ID" in os.environ or "HF_SPACE" in os.environ
3102
+ if is_huggingface_space:
3103
+ print("βœ… Hugging Face Spaces environment detected")
3104
+ print("πŸ€– Using Spaces-optimized configuration")
3105
+
3106
+ # 5. Check for required files with better error handling
3107
  required_files = ["styles/modern.css", "styles/responsive.css", "ui/components.py"]
3108
  missing_files = []
3109
 
 
3115
  if missing_files:
3116
  print(f"⚠️ Missing {len(missing_files)} required files")
3117
  print("⚠️ Some features may not work correctly")
3118
+ # Create minimal fallback CSS files if missing
3119
+ for css_file in ["styles/modern.css", "styles/responsive.css"]:
3120
+ if css_file in missing_files:
3121
+ try:
3122
+ os.makedirs(os.path.dirname(css_file), exist_ok=True)
3123
+ with open(css_file, "w") as f:
3124
+ if "modern.css" in css_file:
3125
+ f.write("/* Modern CSS Fallback */\n:root { --color-primary: #3b82f6; }\n")
3126
+ else:
3127
+ f.write("/* Responsive CSS Fallback */\n@media (max-width: 768px) { .container { padding: 1rem; } }\n")
3128
+ print(f"βœ… Created fallback {css_file}")
3129
+ except Exception as e:
3130
+ print(f"⚠️ Could not create {css_file}: {e}")
3131
 
3132
+ # 6. Import gradio early to prevent threading issues
3133
  try:
3134
+ import gradio as gr
3135
+ logger.info(f"βœ… Gradio {gr.__version__} loaded successfully")
 
 
3136
  except Exception as e:
3137
+ logger.error(f"❌ Failed to load gradio: {e}")
3138
+ print("❌ CRITICAL: Gradio failed to load")
3139
+ raise
3140
 
3141
+ # 7. Start the main application with better error handling
3142
+ try:
3143
+ main()
3144
+ except Exception as e:
3145
+ logger.error(f"❌ Main application crashed: {e}", exc_info=True)
3146
+ print(f"\n❌ FATAL ERROR: {e}")
3147
+ print("πŸ’‘ Troubleshooting tips:")
3148
+ print("1. Check all required files exist")
3149
+ print("2. Verify Python package versions")
3150
+ print("3. Check Hugging Face Spaces logs for details")
3151
+
3152
+ # Try a minimal fallback launch if main() fails
3153
+ try:
3154
+ print("\nπŸ”„ Attempting minimal fallback launch...")
3155
+ import gradio as gr
3156
+
3157
+ def fallback_app():
3158
+ with gr.Blocks(title="ARF Fallback") as demo:
3159
+ gr.Markdown("# 🚨 ARF System Recovery")
3160
+ gr.Markdown("The main application failed, but the system is still running.")
3161
+ gr.Markdown("**Error:** " + str(e))
3162
+ return demo
3163
+
3164
+ demo = fallback_app()
3165
+ demo.launch(
3166
+ server_name="0.0.0.0",
3167
+ server_port=7860,
3168
+ quiet=True,
3169
+ show_error=False
3170
+ )
3171
+ except Exception as fallback_error:
3172
+ print(f"❌ Fallback also failed: {fallback_error}")
3173
+ sys.exit(1)