-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_server.py
More file actions
134 lines (113 loc) Β· 4.55 KB
/
run_server.py
File metadata and controls
134 lines (113 loc) Β· 4.55 KB
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
#!/usr/bin/env python3
"""
FastAPI Server Startup Script
============================
Simple script to start the Intent Detection API server.
Handles basic configuration and provides helpful startup information.
Usage:
python run_server.py
python run_server.py --port 8080
python run_server.py --host 0.0.0.0 --port 9000
Author: Intent Detection System
Date: 2025
"""
import argparse
import sys
import os
from pathlib import Path
# Add current directory to path
sys.path.append(str(Path(__file__).parent))
def check_requirements():
"""Check if required files exist before starting server."""
print("π Checking requirements...")
# Check if model files exist
model_files = [
"models/best_model.pkl",
"models/best_pipeline.pkl"
]
missing_files = []
for file_path in model_files:
if not os.path.exists(file_path):
missing_files.append(file_path)
if missing_files:
print("β Missing required files:")
for file_path in missing_files:
print(f" - {file_path}")
print("\nπ‘ Please train a model first using the notebooks in nbs/")
print(" Run: jupyter notebook nbs/experiment_template.ipynb")
return False
# Check if OpenAI API key is set
api_key = os.getenv("OPENAI_API_KEY")
if not api_key or api_key == "your-openai-api-key-here":
print("β οΈ OpenAI API key not set!")
print(" Set environment variable: export OPENAI_API_KEY='your-key'")
print(" Or create .env file with: OPENAI_API_KEY=your-key")
print(" API will work with ML-only fallback, but LLM features disabled.")
print("β
Requirements check completed!")
return True
def print_startup_info(host: str, port: int):
"""Print helpful startup information."""
print("\n" + "="*60)
print("π INTENT DETECTION API SERVER")
print("="*60)
print(f"π Server URL: http://{host}:{port}")
print(f"π API Docs: http://{host}:{port}/docs")
print(f"π Redoc: http://{host}:{port}/redoc")
print(f"β€οΈ Health Check: http://{host}:{port}/health")
print("\nπ API Endpoints:")
print(f" POST /detect - Main intent detection")
print(f" GET /health - System health status")
print(f" GET / - API information")
print("\nπ Example Usage:")
print(f" curl -X POST http://{host}:{port}/detect \\")
print(f' -H "Content-Type: application/json" \\')
print(f' -d \'{{"query": "I want to cancel my order"}}\'')
print("\nπ§ Configuration:")
print(f" Model: SentenceBERT + Logistic Regression")
print(f" Confidence Threshold: 0.75")
print(f" LLM: OpenAI GPT-3.5-turbo")
print("="*60)
def main():
"""Main function to start the FastAPI server."""
parser = argparse.ArgumentParser(description="Start Intent Detection API server")
parser.add_argument("--host", default="127.0.0.1", help="Host to bind to")
parser.add_argument("--port", type=int, default=8000, help="Port to bind to")
parser.add_argument("--reload", action="store_true", help="Enable auto-reload for development")
parser.add_argument("--workers", type=int, default=1, help="Number of worker processes")
parser.add_argument("--log-level", default="info", choices=["debug", "info", "warning", "error"])
args = parser.parse_args()
# Check requirements
if not check_requirements():
print("\nβ Server startup aborted due to missing requirements.")
print("π‘ Please fix the issues above and try again.")
sys.exit(1)
# Print startup information
print_startup_info(args.host, args.port)
try:
import uvicorn
from app.main import app
print(f"\nπ Starting server on {args.host}:{args.port}...")
print(" Press Ctrl+C to stop the server")
print("-" * 60)
# Start the server
uvicorn.run(
"app.main:app",
host=args.host,
port=args.port,
reload=args.reload,
workers=args.workers,
log_level=args.log_level,
access_log=True
)
except KeyboardInterrupt:
print("\nπ Server stopped by user")
except ImportError as e:
print(f"β Import error: {e}")
print("π‘ Make sure all dependencies are installed:")
print(" pip install -r requirements.txt")
sys.exit(1)
except Exception as e:
print(f"β Server startup failed: {e}")
sys.exit(1)
if __name__ == "__main__":
main()