File size: 5,802 Bytes
62f6391
 
 
 
 
 
 
 
 
 
d57d5a9
62f6391
 
 
 
 
 
 
 
 
 
c598964
 
62f6391
86d1b99
 
 
 
 
 
 
 
 
 
62f6391
 
 
86d1b99
 
 
 
62f6391
c598964
 
 
bfe20a9
62f6391
c598964
af3c3e0
 
 
 
bfe20a9
 
 
62f6391
 
f95c45e
 
 
1ffabfe
 
f95c45e
 
1ffabfe
 
f95c45e
 
 
 
 
 
 
 
 
 
 
62f6391
 
 
 
 
 
 
 
86d1b99
 
 
 
62f6391
 
c598964
af3c3e0
 
c598964
bfe20a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c598964
 
 
 
62f6391
c598964
62f6391
 
 
c598964
86d1b99
 
 
 
 
 
 
 
 
 
 
 
62f6391
 
 
f95c45e
 
 
 
 
 
 
 
 
 
 
 
 
 
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
"""
Hugging Face Spaces entry point.

This file serves as the main entry point for Hugging Face Spaces deployment.
It imports and exposes the FastAPI app from the ai_med_extract package.
"""

import os
import sys
import logging
import importlib.util

# Configure logging for Hugging Face Spaces
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)

# Add the services/ai-service/src directory to the Python path
current_dir = os.path.dirname(os.path.abspath(__file__))
src_dir = os.path.join(current_dir, "services", "ai-service", "src")
if src_dir not in sys.path:
    sys.path.insert(0, src_dir)

# Verify the path is correct
logging.info(f"Added src_dir to Python path: {src_dir}")
logging.info(f"src_dir exists: {os.path.exists(src_dir)}")
if os.path.exists(src_dir):
    logging.info(f"Contents of src_dir: {os.listdir(src_dir)}")
    ai_med_extract_path = os.path.join(src_dir, "ai_med_extract")
    logging.info(f"ai_med_extract_path exists: {os.path.exists(ai_med_extract_path)}")
    if os.path.exists(ai_med_extract_path):
        logging.info(f"Contents of ai_med_extract: {os.listdir(ai_med_extract_path)}")

# Set environment variables for Hugging Face Spaces
os.environ.setdefault("FAST_MODE", "true")
os.environ.setdefault("PRELOAD_SMALL_MODELS", "false")
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "max_split_size_mb:128")
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
os.environ.setdefault("OMP_NUM_THREADS", "1")
os.environ.setdefault("MKL_NUM_THREADS", "1")

# Create a robust app instance with multiple fallback strategies
app = None

# Simplified import strategy with better error handling
try:
    logging.info("Attempting to import from ai_med_extract package...")
    logging.info(f"Python path: {sys.path[:3]}")
    logging.info(f"Current working directory: {os.getcwd()}")
    logging.info(f"Files in current directory: {os.listdir('.')}")
    
    # Direct import approach - simpler and more reliable
    from ai_med_extract.app import create_app, initialize_agents  # type: ignore
    logging.info("Successfully imported create_app and initialize_agents")
    
    # Create the app instance
    try:
        app = create_app()
        logging.info("App instance created successfully")
        logging.info(f"App title: {app.title}")
        logging.info(f"App version: {getattr(app, 'version', 'unknown')}")
    except Exception as e:
        logging.error(f"Failed to create app: {e}")
        import traceback
        logging.error(f"App creation traceback: {traceback.format_exc()}")
        # Create minimal fallback app
        from fastapi import FastAPI
        app = FastAPI(title="Medical AI Service (fallback)")
        
        @app.get("/")
        async def root():
            return {"message": "Medical AI Service - Fallback mode", "error": str(e)}
        
        @app.get("/health")
        async def health():
            return {"status": "degraded", "message": "App creation failed", "error": str(e)}
    
    # Initialize agents with minimal preloading for Hugging Face Spaces
    try:
        initialize_agents(app, preload_small_models=False)
        logging.info("Agents initialized successfully")
    except Exception as e:
        logging.warning(f"Agent initialization failed: {e}")
        logging.info("App will start with basic functionality")
        # Add a basic health endpoint if agents fail
        @app.get("/health")
        async def basic_health():
            return {"status": "degraded", "message": "Agents not initialized", "error": str(e)}
        
except Exception as e:
    logging.error(f"Failed to import from ai_med_extract package: {e}")
    import traceback
    logging.error(f"Full traceback: {traceback.format_exc()}")
    
    # Create a minimal FastAPI app as fallback
    logging.info("Creating minimal fallback app...")
    from fastapi import FastAPI
    app = FastAPI(title="Medical AI Service (fallback)")
    
    @app.get("/")
    async def root():
        return {
            "message": "Medical AI Service - Fallback mode", 
            "error": str(e),
            "status": "degraded"
        }
    
    @app.get("/health")
    async def health():
        return {"status": "degraded", "message": "Fallback mode active"}
    
    @app.get("/docs")
    async def docs():
        return {"message": "API documentation not available in fallback mode"}
    
    @app.get("/redoc")
    async def redoc():
        return {"message": "ReDoc not available in fallback mode"}

# Ensure we have an app instance
if app is None:
    logging.error("No app instance created, creating emergency fallback...")
    from fastapi import FastAPI
    app = FastAPI(title="Medical AI Service (emergency fallback)")
    
    @app.get("/")
    async def root():
        return {"message": "Emergency fallback mode", "status": "error"}
    
    @app.get("/health")
    async def health():
        return {"status": "error", "message": "Emergency fallback mode"}
    
    @app.get("/docs")
    async def docs():
        return {"message": "API documentation not available in emergency mode"}
    
    @app.get("/redoc")
    async def redoc():
        return {"message": "ReDoc not available in emergency mode"}

# Export the app for Hugging Face Spaces
__all__ = ["app"]

# Ensure the app is available at module level
if 'app' not in locals():
    logging.error("No app instance created, creating emergency fallback...")
    from fastapi import FastAPI
    app = FastAPI(title="Medical AI Service (emergency fallback)")
    
    @app.get("/")
    async def root():
        return {"message": "Emergency fallback mode", "status": "error"}
    
    @app.get("/health")
    async def health():
        return {"status": "error", "message": "Emergency fallback mode"}