File size: 10,626 Bytes
e9084d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import sys
import os
import time
import logging
import traceback
from typing import List
from contextlib import asynccontextmanager
from concurrent.futures import ThreadPoolExecutor, as_completed
import asyncio

# Ensure project root is importable
_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _PROJECT_ROOT not in sys.path:
    sys.path.insert(0, _PROJECT_ROOT)

from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

import requests as http_requests

# -- Project imports ----------------------------------------------------------


from backend.models import (
    MatchRequest,
    MatchResponse,
    MatchResult,
    BatchMatchRequest,
    BatchMatchResponse,
    HealthResponse,
    ErrorResponse,
)

from backend.matching_service import perform_match

# =========================================================
# LOGGING
# =========================================================
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)-7s | %(name)s | %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
    force=True,
    handlers=[logging.StreamHandler(sys.stdout)]
)
logger = logging.getLogger("backend_server")


# =========================================================
# LIFESPAN – startup / shutdown hooks
# =========================================================
@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    Startup:
      - Pre-warm embedding models (loaded at import time via model.py)
      - Check CSV data 
    Shutdown:
      - Nothing to close (CSV-based, no database connections)
    """
    logger.info("=" * 60)
    logger.info("Entity Matching backend – Starting up")
    logger.info("=" * 60)

    logger.info("Embedding models loaded (sentence-transformers).")

    try:
        from services.config import pin_city_state_df, name_variation_df
        csv_loaded = not pin_city_state_df.empty
        logger.info("CSV data source: %s (%d pincode rows)",
                     "OK" if csv_loaded else "EMPTY",
                     len(pin_city_state_df))
    except Exception as e:
        logger.warning("CSV data source check failed: %s", e)

   
    logger.info("backend ready to serve requests")
    logger.info("=" * 60)

    yield  # ── app is running ──

    logger.info("Entity Matching backend – Shutting down")


# =========================================================
# APP INSTANCE
# =========================================================
app = FastAPI(
    title="Entity Matching backend",
    description=(
        "Gen AI Record-Level Entity Matching backend.\n\n"
        "Compares two entity records and determines if they represent the same person/entity.\n\n"
        "**Multi-value fields:** `addresses`, `phones`, and `emails` each accept a list "
        "of any length. Matching uses best-of-N for addresses and any-match for phones/emails.\n\n"
        "**Supported matching modes:**\n"
        "- `embedding` (default): Sentence Transformers + Fuzzy matching\n"
        
        "**Input formats:**\n"
        "- Nested (recommended for multiple values): pass `addresses`, `phones`, `emails` as lists\n"
        "- Flat (single address/phone/email): pass uppercase keys like `ADDRESSLINE`, `PHONE`, `EMAIL`"
    ),
    version="8.0.0",
    lifespan=lifespan,
    docs_url="/docs",
    redoc_url="/redoc",
)

# -- CORS middleware ----------------------------------------------------------
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Restrict in production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# =========================================================
# REQUEST LOGGING MIDDLEWARE
# =========================================================
@app.middleware("http")
async def log_requests(request: Request, call_next):
    """Log every request with timing."""
    start = time.perf_counter()
    response = await call_next(request)
    elapsed = (time.perf_counter() - start) * 1000
    logger.info(
        "%s %s – %d (%.1f ms)",
        request.method,
        request.url.path,
        response.status_code,
        elapsed,
    )
    return response


# =========================================================
# GLOBAL EXCEPTION HANDLER
# =========================================================
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    logger.error("Unhandled exception: %s\n%s", exc, traceback.format_exc())
    return JSONResponse(
        status_code=500,
        content={
            "success": False,
            "error": "Internal server error",
            "detail": str(exc),
        },
    )


# =========================================================
# ENDPOINTS
# =========================================================

# ── Health Checks ─────────────────────────────────────────────────────────────
@app.get(
    "/backend/v1/health",
    response_model=HealthResponse,
    tags=["Health"],
    summary="Full system health check",
)
async def health_check():
    """Check the health of all system components."""
    components = {}

    try:
        from services.config import pin_city_state_df
        components["csv_data"] = (
            "healthy" if not pin_city_state_df.empty else "unhealthy"
        )
    except Exception as e:
        components["csv_data"] = f"error: {e}"

    try:
        from services.model import MODEL_STORE
        components["embedding_models"] = "healthy" if MODEL_STORE else "unhealthy"
    except Exception as e:
        components["embedding_models"] = f"error: {e}"

    

    overall = (
        "healthy"
        if all(v == "healthy" for v in components.values() if v != "not_configured")
        else "degraded"
    )
    return HealthResponse(status=overall, version="8.0", components=components)




# ── Single Match ──────────────────────────────────────────────────────────────
@app.post(
    "/backend/v1/match",
    response_model=MatchResponse,
    tags=["Matching"],
    summary="Match two entity records",
    responses={
        200: {"description": "Successful matching result"},
        400: {"model": ErrorResponse, "description": "Invalid input"},
        500: {"model": ErrorResponse, "description": "Internal error"},
    },
)
async def match_records(request: MatchRequest):
    """
    Compare two entity records and determine if they represent the same entity.

    **Multi-value fields:**
    Pass `addresses`, `phones`, and `emails` as lists of any length:
    ```json
    {
      "mode": "embedding",
      "record1": {
        "NAME": "RAJESH KUMAR SHARMA",
        "dob": "15-01-1990",
        "phones": ["9876543210", "9123456789"],
        "addresses": [
          {"addressline": "123 MG Road",     "city": "Bangalore", "state": "Karnataka", "zipcode": "560034"},
          {"addressline": "45 Brigade Road", "city": "Bangalore", "state": "Karnataka", "zipcode": "560025"}
        ]
      },
      "record2": {
        "NAME": "RAJESH K SHARMA",
        "dob": "15/01/1990",
        "phones": ["9876543210"],
        "addresses": [
          {"addressline": "123 Mahatma Gandhi Rd", "city": "Bengaluru", "state": "KA", "zipcode": "560034"}
        ]
      }
    }
    ```

    **Matching strategy for lists:**
    - `addresses`: best-of-N (highest score across all pair combinations)
    - `phones`: any-match (match if any phone pair matches)
    - `emails`: any-match (match if any email pair matches)

    **Modes:**
    - `embedding` (default): Sentence Transformers + RbackenddFuzz
    
    """
    mode = request.mode.value

    
    t0 = time.perf_counter()
    try:
        # Pre-print to terminal specifically for user visibility
        import json
        print("\n\n" + "="*80)
        print(f" NEW MATCH REQUEST RECEIVED (Mode: {mode})")
        print("="*80)
        print(f" RECORD 1 INPUT:\n{json.dumps(request.record1.model_dump(by_alias=True), indent=2)}")
        print(f" RECORD 2 INPUT:\n{json.dumps(request.record2.model_dump(by_alias=True), indent=2)}")
        print("-" * 80)

        # perform_match is synchronous (CPU + IO bound); run in thread pool
        # so it doesn't block the asyncio event loop.
        result = await asyncio.to_thread(
            perform_match, request.record1, request.record2, mode=mode
        )
        elapsed_ms = (time.perf_counter() - t0) * 1000
        logger.info(
            "Match complete β€” decision=%s mode=%s time=%.1fms",
            result["overall_decision"], mode, elapsed_ms,
        )
        
        # Post-print to terminal specifically for user visibility
        print("πŸ“€ MATCH RESULT OUT:\n" + json.dumps({
            "overall_decision": result["overall_decision"],
            "reason": result["reason"],
            "field_scores": result["field_scores"]
        }, indent=2))
        print("="*80 + "\n\n")

        return MatchResponse(
            success=True,
            result=MatchResult(
                overall_decision=result["overall_decision"],
                reason=result["reason"],
                field_scores=result["field_scores"],
                mode=mode,
            ),
            processing_time_ms=round(elapsed_ms, 2),
        )
    except Exception as e:
        elapsed_ms = (time.perf_counter() - t0) * 1000
        logger.error("Match failed: %s\n%s", e, traceback.format_exc())
        return MatchResponse(
            success=False,
            error=str(e),
            processing_time_ms=round(elapsed_ms, 2),
        )



# =========================================================
# ROOT / INFO
# =========================================================
@app.get("/", tags=["Info"], include_in_schema=False)
async def root():
    return {
        "service": "Entity Matching backend",
        "version": "8.0.0",
        "docs":    "/docs",
        "health":  "/backend/v1/health",
    }


# =========================================================
# MAIN (for direct execution: python backend/server.py)
# =========================================================
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "backend.server:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info",
    )