itsbava commited on
Commit
ff08aee
·
verified ·
1 Parent(s): 1897004

Upload 4 files

Browse files
Files changed (1) hide show
  1. handler.py +83 -7
handler.py CHANGED
@@ -1,10 +1,86 @@
1
- from app import app
 
 
 
 
 
 
2
 
3
- # This is the handler that HuggingFace expects
4
- def handler(event, context):
5
- return app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- # For direct FastAPI deployment
 
 
 
 
8
  if __name__ == "__main__":
9
- import uvicorn
10
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
 
 
1
+ from typing import Dict, List, Any
2
+ import json
3
+ import base64
4
+ import asyncio
5
+ import uvicorn
6
+ from threading import Thread
7
+ import time
8
 
9
+ class EndpointHandler:
10
+ def __init__(self, path=""):
11
+ """Initialize the endpoint handler"""
12
+ self.path = path
13
+ self.app = None
14
+ self.server_thread = None
15
+ self._initialize_app()
16
+
17
+ def _initialize_app(self):
18
+ """Initialize the FastAPI app"""
19
+ try:
20
+ from app import app
21
+ self.app = app
22
+ print("FastAPI app loaded successfully")
23
+ except Exception as e:
24
+ print(f"Error loading app: {e}")
25
+ raise
26
+
27
+ def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
28
+ """
29
+ Handle inference requests from HuggingFace
30
+ This method gets called for each request
31
+ """
32
+ try:
33
+ # Start the FastAPI server if not already running
34
+ if not self.server_thread or not self.server_thread.is_alive():
35
+ self._start_server()
36
+
37
+ # For now, return a simple response
38
+ # The actual API calls will go through FastAPI endpoints
39
+ return {
40
+ "status": "success",
41
+ "message": "FastAPI server is running",
42
+ "endpoints": [
43
+ "/health",
44
+ "/extract_embeddings_batch",
45
+ "/create_faiss_index",
46
+ "/search_faiss"
47
+ ],
48
+ "server_url": "http://0.0.0.0:8000"
49
+ }
50
+
51
+ except Exception as e:
52
+ return {
53
+ "status": "error",
54
+ "message": str(e)
55
+ }
56
+
57
+ def _start_server(self):
58
+ """Start the FastAPI server in a background thread"""
59
+ def run_server():
60
+ try:
61
+ uvicorn.run(
62
+ self.app,
63
+ host="0.0.0.0",
64
+ port=8000,
65
+ log_level="info"
66
+ )
67
+ except Exception as e:
68
+ print(f"Server error: {e}")
69
+
70
+ self.server_thread = Thread(target=run_server, daemon=True)
71
+ self.server_thread.start()
72
+
73
+ # Give the server time to start
74
+ time.sleep(5)
75
+ print("FastAPI server started in background thread")
76
 
77
+ # Create the handler instance that HuggingFace expects
78
+ def get_handler():
79
+ return EndpointHandler()
80
+
81
+ # For direct testing
82
  if __name__ == "__main__":
83
+ handler = EndpointHandler()
84
+ # Test the handler
85
+ result = handler({"test": "data"})
86
+ print(result)