File size: 20,235 Bytes
72b7090
80ddd9c
 
8c694d8
6776a36
d80ba6a
6776a36
34d316c
 
61c6f19
72b7090
6873332
72b7090
 
6776a36
9d2460e
72b7090
c82aa52
 
61c6f19
34d316c
 
 
 
 
9d2460e
 
34d316c
 
80ddd9c
72b7090
9d2460e
 
 
72b7090
9d2460e
 
72b7090
34d316c
 
 
 
 
 
6d59d9b
 
72b7090
 
 
 
 
 
 
6d59d9b
6776a36
 
72b7090
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61c6f19
6776a36
 
c82aa52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6776a36
 
 
 
34d316c
 
 
 
 
 
 
 
 
d80ba6a
6d59d9b
72b7090
 
 
 
 
 
6d59d9b
6776a36
34d316c
6776a36
34d316c
72b7090
 
f9d7ba8
72b7090
 
b320785
6776a36
72b7090
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
945ba15
80ddd9c
72b7090
945ba15
a336ac6
72b7090
 
945ba15
a336ac6
61c6f19
a336ac6
 
72b7090
 
 
80ddd9c
9d2460e
 
 
 
6873332
9d2460e
61c6f19
9d2460e
 
61c6f19
9d2460e
 
72b7090
 
 
 
80ddd9c
72b7090
 
80ddd9c
 
 
 
72b7090
c682e10
72b7090
80ddd9c
 
 
 
 
72b7090
 
 
 
 
80ddd9c
 
 
 
 
 
 
 
 
 
 
72b7090
80ddd9c
 
 
72b7090
 
c682e10
80ddd9c
 
 
72b7090
9d2460e
72b7090
9d2460e
72b7090
 
 
 
 
c682e10
72b7090
 
 
 
 
 
 
 
6873332
72b7090
 
 
 
 
 
 
 
6873332
 
72b7090
6873332
632a290
 
 
3d6e38a
d80ba6a
8c694d8
c682e10
 
 
 
 
 
 
80ddd9c
c682e10
80ddd9c
 
c682e10
 
80ddd9c
 
 
c682e10
 
 
 
 
 
 
 
 
 
80ddd9c
 
 
c682e10
 
 
80ddd9c
c682e10
 
80ddd9c
c682e10
 
 
 
 
 
 
 
80ddd9c
 
 
 
 
 
 
c682e10
 
 
80ddd9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c682e10
 
 
80ddd9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c682e10
80ddd9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c682e10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80ddd9c
 
 
 
 
 
c682e10
 
 
 
 
80ddd9c
 
 
 
 
c682e10
 
80ddd9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c682e10
80ddd9c
 
c682e10
 
80ddd9c
 
c682e10
 
 
 
 
80ddd9c
 
 
c682e10
 
 
 
 
 
 
 
 
 
 
 
 
80ddd9c
 
 
 
 
 
 
 
72b7090
80ddd9c
 
 
 
 
 
 
 
 
 
 
 
 
 
72b7090
80ddd9c
 
c682e10
80ddd9c
 
 
 
 
 
 
c682e10
80ddd9c
 
 
 
 
 
 
 
72b7090
80ddd9c
 
c682e10
80ddd9c
 
 
 
 
c682e10
 
80ddd9c
c682e10
72b7090
 
 
c682e10
 
80ddd9c
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648

# # app.py

# app.py
import uvicorn
import numpy as np
import cv2
import boto3
import os
import json
import time
import requests
from datetime import datetime
from fastapi import FastAPI, UploadFile, File, HTTPException, Header
from rapidocr_onnxruntime import RapidOCR
from openai import OpenAI
from pymongo import MongoClient
from pymongo.errors import PyMongoError
from botocore.exceptions import BotoCoreError, ClientError
# ---------------- ENV CONFIG ----------------
DO_KEY_ID = os.getenv("DO_SPACES_KEY_ID")
DO_SECRET_KEY = os.getenv("DO_SPACES_SECRET_KEY")
DO_REGION = os.getenv("DO_SPACES_REGION", "blr1")
DO_ENDPOINT = os.getenv("DO_SPACES_ENDPOINT")
DO_BUCKET = os.getenv("DO_SPACES_BUCKET", "milestone")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")

FOLDER = "OCR_Images"

CATEGORY_API_URL = "https://logicgoinfotechspaces-expensecategorizenotes.hf.space"

if not OPENAI_API_KEY:
    raise RuntimeError("OPENAI_API_KEY missing!")

# ---------------- OPENAI ----------------
client = OpenAI(api_key=OPENAI_API_KEY)

# ---------------- S3 ----------------
s3 = boto3.client(
    "s3",
    region_name=DO_REGION,
    endpoint_url=DO_ENDPOINT,
    aws_access_key_id=DO_KEY_ID,
    aws_secret_access_key=DO_SECRET_KEY,
)

# ---------------- MONGODB ----------------
MONGO_URI = os.getenv("MONGO_URI")
mongo_client = MongoClient(MONGO_URI)
mongo_db = mongo_client["expense"]
api_logs_col = mongo_db["api_logs"]

# ---------------- APP ----------------
app = FastAPI()
ocr_engine = RapidOCR()

# ---------------- HELPERS ----------------
def ist_now():
    return datetime.now().strftime("%d-%m-%Y %H:%M:%S:IST")

def log_api_event(
    *,
    status: str,
    response_time: float,
    user_id: str | None,
    error_message: str | None = None
):
    payload = {
        "name": "Receipt Scanner",
        "status": status,
        "date": ist_now(),
        "response_time": round(response_time, 3),
    }

    if user_id:
        payload["user_id"] = user_id

    if error_message:
        payload["error_message"] = error_message

    try:
        api_logs_col.insert_one(payload)
    except Exception:
        pass  # never break API because of logging failure

# ---------------- ROUTES ----------------
@app.get("/health")
async def health():
    health_report = {
        "service": "Receipt Scanner API",
        "status": "healthy",
        "checks": {}
    }

    # ---------------- MongoDB ----------------
    try:
        mongo_client.admin.command("ping")
        health_report["checks"]["mongodb"] = "ok"
    except PyMongoError as e:
        health_report["checks"]["mongodb"] = f"fail: {str(e)}"
        health_report["status"] = "degraded"

    # ---------------- OpenAI ----------------
    try:
        # very light call, does not consume tokens
        client.models.list()
        health_report["checks"]["openai"] = "ok"
    except Exception as e:
        health_report["checks"]["openai"] = f"fail: {str(e)}"
        health_report["status"] = "degraded"

    # ---------------- DO Spaces / S3 ----------------
    try:
        s3.head_bucket(Bucket=DO_BUCKET)
        health_report["checks"]["object_storage"] = "ok"
    except (BotoCoreError, ClientError) as e:
        health_report["checks"]["object_storage"] = f"fail: {str(e)}"
        health_report["status"] = "degraded"

    # ---------------- OCR Engine ----------------
    try:
        if ocr_engine is None:
            raise RuntimeError("OCR engine not initialized")
        health_report["checks"]["ocr"] = "ok"
    except Exception as e:
        health_report["checks"]["ocr"] = f"fail: {str(e)}"
        health_report["status"] = "degraded"

    # ---------------- Overall ----------------
    health_report["timestamp"] = datetime.utcnow().isoformat()

    return health_report

@app.post("/upload")
async def upload_image(file: UploadFile = File(...)):
    try:
        file_bytes = await file.read()
        image_key = f"{FOLDER}/{file.filename}"

        s3.put_object(
            Bucket=DO_BUCKET,
            Key=image_key,
            Body=file_bytes,
            ContentType=file.content_type,
            ACL="private"
        )

        return {
            "status": "success",
            "message": "Uploaded successfully",
            "image_id": image_key,
            "local_path": "/mnt/data/image.png"
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/generate/{image_id:path}")
async def generate(
    image_id: str,
    user_id: str | None = Header(default=None, alias="user_id")
):
    start_time = time.time()

    try:
        # -------- DOWNLOAD IMAGE --------
        try:
            obj = s3.get_object(Bucket=DO_BUCKET, Key=image_id)
            raw_bytes = obj["Body"].read()
        except Exception:
            local_path = "/mnt/data/image.png"
            if os.path.exists(local_path):
                with open(local_path, "rb") as f:
                    raw_bytes = f.read()
            else:
                raise HTTPException(status_code=404, detail="Image not found")

        img_array = np.frombuffer(raw_bytes, np.uint8)
        img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)

        if img is None:
            raise HTTPException(status_code=400, detail="Unable to decode image")

        # -------- OCR --------
        result, _ = ocr_engine(img)
        if not result:
            raise RuntimeError("OCR returned empty result")

        full_text = "\n".join([text for _, text, _ in result])

        confidences = [conf for _, _, conf in result if isinstance(conf, (int, float))]
        avg_confidence = sum(confidences) / len(confidences) if confidences else 0

        if avg_confidence < 0.70:
            response_time = time.time() - start_time
            log_api_event(
                status="fail",
                response_time=response_time,
                user_id=user_id,
                error_message="Low OCR confidence"
            )

            return {
                "status": "fail",
                "message": "Upload image with more clarity or enter manually.",
                "image_id": image_id,
                "raw_text": full_text,
                "confidence": round(avg_confidence, 3),
            }

        # -------- GPT SCHEMA --------
        schema = {
            "name": "extract_expense_details",
            "schema": {
                "type": "object",
                "properties": {
                    "total_amount": {"type": "number"},
                    "date": {"type": "string"},
                    "time": {"type": "string"},
                    "payment_type": {
                        "type": "string",
                        "enum": ["cash", "card", "upi", "unknown"]
                    },
                    "notes": {"type": "string"}
                },
                "required": ["total_amount"]
            }
        }

        prompt = f"""
Extract expense details from OCR text below:

\"\"\"
{full_text}
\"\"\"

Rules:
- Do not guess missing values → use "unknown"
- Notes format:
"Spent <total_amount> on <merchant_name> on <date>."
"""

        response = client.chat.completions.create(
            model="gpt-4o-mini",
            response_format={"type": "json_schema", "json_schema": schema},
            messages=[
                {"role": "system", "content": "You are an expert in receipt parsing."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.1
        )

        parsed = json.loads(response.choices[0].message.content)

        parsed.setdefault("date", "unknown")
        parsed.setdefault("time", "unknown")
        parsed.setdefault("payment_type", "cash")
        parsed.setdefault("notes", "unknown")

        # Set payment_type to "cash" if it's "unknown"
        if parsed.get("payment_type") == "unknown":
            parsed["payment_type"] = "cash"

        # -------- CATEGORY API --------
        try:
            cat_response = requests.post(
                f"{CATEGORY_API_URL}/api/v1/categorize",
                json={
                    "notes": parsed["notes"],
                    "user_id": user_id
                },
                timeout=10
            )

            if cat_response.status_code == 200:
                cat_data = cat_response.json()
                if cat_data.get("status") == "success" and cat_data.get("data"):
                    data = cat_data["data"]
                    parsed["headcategory_id"] = data.get("headcategory_id")
                    parsed["headcategory_title"] = data.get("headcategory_title")
                    parsed["category_id"] = data.get("category_id")
                    parsed["category_title"] = data.get("category_title")
                else:
                    parsed["headcategory_id"] = None
                    parsed["headcategory_title"] = None
                    parsed["category_id"] = None
                    parsed["category_title"] = None
            else:
                parsed["headcategory_id"] = None
                parsed["headcategory_title"] = None
                parsed["category_id"] = None
                parsed["category_title"] = None

        except Exception:
            parsed["headcategory_id"] = None
            parsed["headcategory_title"] = None
            parsed["category_id"] = None
            parsed["category_title"] = None

        response_time = time.time() - start_time

        log_api_event(
            status="success",
            response_time=response_time,
            user_id=user_id
        )

        return {
            "status": "success",
            "message": "Receipt processed and logged in DB",
            "image_id": image_id,
            "confidence": round(avg_confidence, 3),
            "raw_text": full_text,
            "parsed": parsed,
        }

    except Exception as e:
        response_time = time.time() - start_time

        log_api_event(
            status="fail",
            response_time=response_time,
            user_id=user_id,
            error_message=str(e)
        )

        raise HTTPException(status_code=500, detail=str(e))

@app.get("/ping")
def ping():
    return {"status": "alive"}

if __name__ == "__main__":
    uvicorn.run("app:app", host="0.0.0.0", port=7860)

# import uvicorn
# import numpy as np
# import cv2
# import boto3
# import os
# import json
# import time
# import requests
# from datetime import datetime
# from fastapi import FastAPI, UploadFile, File, HTTPException, Header
# from rapidocr_onnxruntime import RapidOCR
# from openai import OpenAI
# from pymongo import MongoClient
# from pymongo.errors import PyMongoError
# from botocore.exceptions import BotoCoreError, ClientError
# # ---------------- ENV CONFIG ----------------
# DO_KEY_ID = os.getenv("DO_SPACES_KEY_ID")
# DO_SECRET_KEY = os.getenv("DO_SPACES_SECRET_KEY")
# DO_REGION = os.getenv("DO_SPACES_REGION", "blr1")
# DO_ENDPOINT = os.getenv("DO_SPACES_ENDPOINT")
# DO_BUCKET = os.getenv("DO_SPACES_BUCKET", "milestone")
# OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")

# FOLDER = "OCR_Images"

# CATEGORY_API_URL = os.getenv("CATEGORY_API_URL")
# NOTES_CATEGORIZER_URL = os.getenv("NOTES_CATEGORIZER_URL")

# if not OPENAI_API_KEY:
#     raise RuntimeError("OPENAI_API_KEY missing!")

# # ---------------- OPENAI ----------------
# client = OpenAI(api_key=OPENAI_API_KEY)

# # ---------------- S3 ----------------
# s3 = boto3.client(
#     "s3",
#     region_name=DO_REGION,
#     endpoint_url=DO_ENDPOINT,
#     aws_access_key_id=DO_KEY_ID,
#     aws_secret_access_key=DO_SECRET_KEY,
# )

# # ---------------- MONGODB ----------------
# MONGO_URI = os.getenv("MONGO_URI")
# mongo_client = MongoClient(MONGO_URI)
# mongo_db = mongo_client["expense"]
# api_logs_col = mongo_db["api_logs"]

# # ---------------- APP ----------------
# app = FastAPI()
# ocr_engine = RapidOCR()

# # ---------------- HELPERS ----------------
# def ist_now():
#     return datetime.now().strftime("%d-%m-%Y %H:%M:%S:IST")

# def log_api_event(
#     *,
#     status: str,
#     response_time: float,
#     user_id: str | None,
#     error_message: str | None = None
# ):
#     payload = {
#         "name": "Receipt Scanner",
#         "status": status,
#         "date": ist_now(),
#         "response_time": round(response_time, 3),
#     }

#     if user_id:
#         payload["user_id"] = user_id

#     if error_message:
#         payload["error_message"] = error_message

#     try:
#         api_logs_col.insert_one(payload)
#     except Exception:
#         pass  # never break API because of logging failure

# # ---------------- ROUTES ----------------
# @app.get("/health")
# async def health():
#     health_report = {
#         "service": "Receipt Scanner API",
#         "status": "healthy",
#         "checks": {}
#     }

#     # ---------------- MongoDB ----------------
#     try:
#         mongo_client.admin.command("ping")
#         health_report["checks"]["mongodb"] = "ok"
#     except PyMongoError as e:
#         health_report["checks"]["mongodb"] = f"fail: {str(e)}"
#         health_report["status"] = "degraded"

#     # ---------------- OpenAI ----------------
#     try:
#         # very light call, does not consume tokens
#         client.models.list()
#         health_report["checks"]["openai"] = "ok"
#     except Exception as e:
#         health_report["checks"]["openai"] = f"fail: {str(e)}"
#         health_report["status"] = "degraded"

#     # ---------------- DO Spaces / S3 ----------------
#     try:
#         s3.head_bucket(Bucket=DO_BUCKET)
#         health_report["checks"]["object_storage"] = "ok"
#     except (BotoCoreError, ClientError) as e:
#         health_report["checks"]["object_storage"] = f"fail: {str(e)}"
#         health_report["status"] = "degraded"

#     # ---------------- OCR Engine ----------------
#     try:
#         if ocr_engine is None:
#             raise RuntimeError("OCR engine not initialized")
#         health_report["checks"]["ocr"] = "ok"
#     except Exception as e:
#         health_report["checks"]["ocr"] = f"fail: {str(e)}"
#         health_report["status"] = "degraded"

#     # ---------------- Overall ----------------
#     health_report["timestamp"] = datetime.utcnow().isoformat()

#     return health_report

# @app.post("/upload")
# async def upload_image(file: UploadFile = File(...)):
#     try:
#         file_bytes = await file.read()
#         image_key = f"{FOLDER}/{file.filename}"

#         s3.put_object(
#             Bucket=DO_BUCKET,
#             Key=image_key,
#             Body=file_bytes,
#             ContentType=file.content_type,
#             ACL="private"
#         )

#         return {
#             "status": "success",
#             "message": "Uploaded successfully",
#             "image_id": image_key,
#             "local_path": "/mnt/data/image.png"
#         }

#     except Exception as e:
#         raise HTTPException(status_code=500, detail=str(e))

# @app.post("/generate/{image_id:path}")
# async def generate(
#     image_id: str,
#     user_id: str | None = Header(default=None, alias="user_id")
# ):
#     start_time = time.time()

#     try:
#         # -------- DOWNLOAD IMAGE --------
#         try:
#             obj = s3.get_object(Bucket=DO_BUCKET, Key=image_id)
#             raw_bytes = obj["Body"].read()
#         except Exception:
#             local_path = "/mnt/data/image.png"
#             if os.path.exists(local_path):
#                 with open(local_path, "rb") as f:
#                     raw_bytes = f.read()
#             else:
#                 raise HTTPException(status_code=404, detail="Image not found")

#         img_array = np.frombuffer(raw_bytes, np.uint8)
#         img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)

#         if img is None:
#             raise HTTPException(status_code=400, detail="Unable to decode image")

#         # -------- OCR --------
#         result, _ = ocr_engine(img)
#         if not result:
#             raise RuntimeError("OCR returned empty result")

#         full_text = "\n".join([text for _, text, _ in result])

#         confidences = [conf for _, _, conf in result if isinstance(conf, (int, float))]
#         avg_confidence = sum(confidences) / len(confidences) if confidences else 0

#         if avg_confidence < 0.70:
#             response_time = time.time() - start_time
#             log_api_event(
#                 status="fail",
#                 response_time=response_time,
#                 user_id=user_id,
#                 error_message="Low OCR confidence"
#             )

#             return {
#                 "status": "fail",
#                 "message": "Upload image with more clarity or enter manually.",
#                 "image_id": image_id,
#                 "raw_text": full_text,
#                 "confidence": round(avg_confidence, 3),
#             }

#         # -------- GPT SCHEMA --------
#         schema = {
#             "name": "extract_expense_details",
#             "schema": {
#                 "type": "object",
#                 "properties": {
#                     "total_amount": {"type": "number"},
#                     "label": {"type": "string"},
#                     "date": {"type": "string"},
#                     "time": {"type": "string"},
#                     "payment_type": {
#                         "type": "string",
#                         "enum": ["cash", "card", "upi", "unknown"]
#                     },
#                     "notes": {"type": "string"}
#                 },
#                 "required": ["total_amount", "label"]
#             }
#         }

#         prompt = f"""
# Extract expense details from OCR text below:

# \"\"\"
# {full_text}
# \"\"\"

# Rules:
# - Do not guess missing values → use "unknown"
# - Notes format:
# "Spent <total_amount> on <label> on <date>."
# """

#         response = client.chat.completions.create(
#             model="gpt-4o-mini",
#             response_format={"type": "json_schema", "json_schema": schema},
#             messages=[
#                 {"role": "system", "content": "You are an expert in receipt parsing."},
#                 {"role": "user", "content": prompt}
#             ],
#             temperature=0.1
#         )

#         parsed = json.loads(response.choices[0].message.content)

#         parsed.setdefault("date", "unknown")
#         parsed.setdefault("time", "unknown")
#         parsed.setdefault("payment_type", "unknown")
#         parsed.setdefault("notes", "unknown")

#         # -------- CATEGORY API --------
#         try:
#             cat_response = requests.post(
#                 NOTES_CATEGORIZER_URL,
#                 json={"notes": parsed["notes"]},
#                 timeout=10
#             )

#             if cat_response.status_code == 200:
#                 cat_data = cat_response.json()
#                 parsed["category"] = cat_data.get("subcategory", "unknown")
#                 parsed["category_title"] = cat_data.get("title")
#             else:
#                 parsed["category"] = "unknown"
#                 parsed["category_title"] = None

#         except Exception:
#             parsed["category"] = "unknown"
#             parsed["category_title"] = None

#         response_time = time.time() - start_time

#         log_api_event(
#             status="success",
#             response_time=response_time,
#             user_id=user_id
#         )

#         return {
#             "status": "success",
#             "message": "Receipt processed and logged in DB",
#             "image_id": image_id,
#             "confidence": round(avg_confidence, 3),
#             "raw_text": full_text,
#             "parsed": parsed,
#         }

#     except Exception as e:
#         response_time = time.time() - start_time

#         log_api_event(
#             status="fail",
#             response_time=response_time,
#             user_id=user_id,
#             error_message=str(e)
#         )

#         raise HTTPException(status_code=500, detail=str(e))

# @app.get("/ping")
# def ping():
#     return {"status": "alive"}

# if __name__ == "__main__":
#     uvicorn.run("app:app", host="0.0.0.0", port=7860)