File size: 11,007 Bytes
c3aef13
dda5c3b
03eefac
c3aef13
 
 
 
 
 
 
03eefac
5861022
 
03eefac
 
5861022
03eefac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5861022
 
 
03eefac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5861022
c3aef13
909d9bf
03eefac
 
 
c3aef13
 
dda5c3b
 
 
 
 
 
 
 
c3aef13
 
 
 
03eefac
 
c3aef13
909d9bf
03eefac
 
 
 
 
 
 
 
c3aef13
 
03eefac
 
 
 
c3aef13
03eefac
 
0610fdd
03eefac
 
 
 
 
 
 
 
 
 
 
 
 
 
c3aef13
03eefac
 
 
 
 
 
 
 
 
 
 
 
c3aef13
 
 
03eefac
c3aef13
 
 
 
 
03eefac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3aef13
 
 
03eefac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3aef13
 
 
 
 
 
 
 
 
 
 
 
 
03eefac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3aef13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a6cb95
 
 
 
 
 
 
 
 
c3aef13
 
 
 
 
 
03eefac
5861022
c3aef13
03eefac
 
 
dda5c3b
0610fdd
03eefac
 
 
 
 
 
 
c3aef13
 
 
 
 
 
 
 
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from typing import List
import torch
import uvicorn

from models.schemas import EmbeddingRequest, EmbeddingResponse, ModelInfo
from utils.helpers import load_models, get_embeddings, cleanup_memory

# Global model cache
models_cache = {}

# Load jina-v3 at startup (most important model)
STARTUP_MODEL = "jina-v3"

@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan handler for startup and shutdown"""
    # Startup - load jina-v3 model
    try:
        global models_cache
        print(f"Loading startup model: {STARTUP_MODEL}...")
        models_cache = load_models([STARTUP_MODEL])
        print(f"Startup model loaded successfully: {list(models_cache.keys())}")
        yield
    except Exception as e:
        print(f"Failed to load startup model: {str(e)}")
        # Continue anyway - jina-v3 can be loaded on demand if startup fails
        yield
    finally:
        # Shutdown - cleanup resources
        cleanup_memory()

def ensure_model_loaded(model_name: str, max_length_limit: int):
    """Load a specific model on demand if not already loaded"""
    global models_cache
    if model_name not in models_cache:
        try:
            print(f"Loading model on demand: {model_name}...")
            new_models = load_models([model_name])
            models_cache.update(new_models)
            print(f"Model {model_name} loaded successfully!")
        except Exception as e:
            print(f"Failed to load model {model_name}: {str(e)}")
            raise HTTPException(status_code=500, detail=f"Model {model_name} loading failed: {str(e)}")

def validate_request_for_model(request: EmbeddingRequest, model_name: str, max_length_limit: int):
    """Validate request parameters for specific model"""
    if not request.texts:
        raise HTTPException(status_code=400, detail="No texts provided")
    
    if len(request.texts) > 50:
        raise HTTPException(status_code=400, detail="Maximum 50 texts per request")
    
    if request.max_length is not None and request.max_length > max_length_limit:
        raise HTTPException(status_code=400, detail=f"Max length for {model_name} is {max_length_limit}")

app = FastAPI(
    title="Multilingual & Legal Embedding API",
    description="Multi-model embedding API with dedicated endpoints per model",
    version="4.0.0",
    lifespan=lifespan
)

# Add CORS middleware to allow cross-origin requests
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # In production, specify actual domains
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def root():
    return {
        "message": "Multilingual & Legal Embedding API - Endpoint Per Model",
        "version": "4.0.0",
        "status": "running",
        "docs": "/docs",
        "startup_model": STARTUP_MODEL,
        "available_endpoints": {
            "jina-v3": "/embed/jina-v3",
            "roberta-ca": "/embed/roberta-ca", 
            "jina": "/embed/jina",
            "robertalex": "/embed/robertalex",
            "legal-bert": "/embed/legal-bert"
        }
    }

# Jina v3 - Multilingual (loads at startup)
@app.post("/embed/jina-v3", response_model=EmbeddingResponse)
async def embed_jina_v3(request: EmbeddingRequest):
    """Generate embeddings using Jina v3 model (multilingual)"""
    try:
        ensure_model_loaded("jina-v3", 8192)
        validate_request_for_model(request, "jina-v3", 8192)
        
        embeddings = get_embeddings(
            request.texts,
            "jina-v3",
            models_cache,
            request.normalize,
            request.max_length
        )
        
        return EmbeddingResponse(
            embeddings=embeddings,
            model_used="jina-v3",
            dimensions=len(embeddings[0]) if embeddings else 0,
            num_texts=len(request.texts)
        )
        
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")

# Catalan RoBERTa
@app.post("/embed/roberta-ca", response_model=EmbeddingResponse)
async def embed_roberta_ca(request: EmbeddingRequest):
    """Generate embeddings using Catalan RoBERTa model"""
    try:
        ensure_model_loaded("roberta-ca", 512)
        validate_request_for_model(request, "roberta-ca", 512)
        
        embeddings = get_embeddings(
            request.texts,
            "roberta-ca",
            models_cache,
            request.normalize,
            request.max_length
        )
        
        return EmbeddingResponse(
            embeddings=embeddings,
            model_used="roberta-ca",
            dimensions=len(embeddings[0]) if embeddings else 0,
            num_texts=len(request.texts)
        )
        
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")

# Jina v2 - Spanish/English
@app.post("/embed/jina", response_model=EmbeddingResponse)
async def embed_jina(request: EmbeddingRequest):
    """Generate embeddings using Jina v2 Spanish/English model"""
    try:
        ensure_model_loaded("jina", 8192)
        validate_request_for_model(request, "jina", 8192)
        
        embeddings = get_embeddings(
            request.texts,
            "jina",
            models_cache,
            request.normalize,
            request.max_length
        )
        
        return EmbeddingResponse(
            embeddings=embeddings,
            model_used="jina",
            dimensions=len(embeddings[0]) if embeddings else 0,
            num_texts=len(request.texts)
        )
        
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")

# RoBERTalex - Spanish Legal
@app.post("/embed/robertalex", response_model=EmbeddingResponse)
async def embed_robertalex(request: EmbeddingRequest):
    """Generate embeddings using RoBERTalex Spanish legal model"""
    try:
        ensure_model_loaded("robertalex", 512)
        validate_request_for_model(request, "robertalex", 512)
        
        embeddings = get_embeddings(
            request.texts,
            "robertalex",
            models_cache,
            request.normalize,
            request.max_length
        )
        
        return EmbeddingResponse(
            embeddings=embeddings,
            model_used="robertalex",
            dimensions=len(embeddings[0]) if embeddings else 0,
            num_texts=len(request.texts)
        )
        
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")

# Legal BERT - English Legal
@app.post("/embed/legal-bert", response_model=EmbeddingResponse)
async def embed_legal_bert(request: EmbeddingRequest):
    """Generate embeddings using Legal BERT English model"""
    try:
        ensure_model_loaded("legal-bert", 512)
        validate_request_for_model(request, "legal-bert", 512)
        
        embeddings = get_embeddings(
            request.texts,
            "legal-bert",
            models_cache,
            request.normalize,
            request.max_length
        )
        
        return EmbeddingResponse(
            embeddings=embeddings,
            model_used="legal-bert",
            dimensions=len(embeddings[0]) if embeddings else 0,
            num_texts=len(request.texts)
        )
        
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")

@app.get("/models", response_model=List[ModelInfo])
async def list_models():
    """List available models and their specifications"""
    return [
        ModelInfo(
            model_id="jina-v3",
            name="jinaai/jina-embeddings-v3",
            dimensions=1024,
            max_sequence_length=8192,
            languages=["Multilingual"],
            model_type="multilingual",
            description="Latest Jina v3 with superior multilingual performance - loaded at startup"
        ),
        ModelInfo(
            model_id="roberta-ca",
            name="projecte-aina/roberta-large-ca-v2",
            dimensions=1024,
            max_sequence_length=512,
            languages=["Catalan"],
            model_type="general",
            description="Catalan RoBERTa-large model trained on large corpus"
        ),
        ModelInfo(
            model_id="jina",
            name="jinaai/jina-embeddings-v2-base-es",
            dimensions=768,
            max_sequence_length=8192,
            languages=["Spanish", "English"],
            model_type="bilingual",
            description="Bilingual Spanish-English embeddings with long context support"
        ),
        ModelInfo(
            model_id="robertalex",
            name="PlanTL-GOB-ES/RoBERTalex",
            dimensions=768,
            max_sequence_length=512,
            languages=["Spanish"],
            model_type="legal domain",
            description="Spanish legal domain specialized embeddings"
        ),
        ModelInfo(
            model_id="legal-bert",
            name="nlpaueb/legal-bert-base-uncased",
            dimensions=768,
            max_sequence_length=512,
            languages=["English"],
            model_type="legal domain",
            description="English legal domain BERT model"
        )
    ]

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    startup_loaded = STARTUP_MODEL in models_cache
    
    return {
        "status": "healthy" if startup_loaded else "partial",
        "startup_model": STARTUP_MODEL,
        "startup_model_loaded": startup_loaded,
        "available_models": list(models_cache.keys()),
        "models_count": len(models_cache),
        "endpoints": {
            "jina-v3": f"/embed/jina-v3 {'(ready)' if 'jina-v3' in models_cache else '(loads on demand)'}",
            "roberta-ca": f"/embed/roberta-ca {'(ready)' if 'roberta-ca' in models_cache else '(loads on demand)'}",
            "jina": f"/embed/jina {'(ready)' if 'jina' in models_cache else '(loads on demand)'}",
            "robertalex": f"/embed/robertalex {'(ready)' if 'robertalex' in models_cache else '(loads on demand)'}",
            "legal-bert": f"/embed/legal-bert {'(ready)' if 'legal-bert' in models_cache else '(loads on demand)'}"
        }
    }

if __name__ == "__main__":
    # Set multi-threading for CPU
    torch.set_num_threads(8)
    torch.set_num_interop_threads(1)
    
    uvicorn.run(app, host="0.0.0.0", port=7860)