File size: 16,399 Bytes
bcb42d8 fcf59c8 bcb42d8 fcf59c8 bcb42d8 fcf59c8 bcb42d8 fcf59c8 bcb42d8 fcf59c8 bcb42d8 fcf59c8 bcb42d8 d9a631f 77fc5e6 56c9035 fcf59c8 77fc5e6 bcb42d8 56c9035 bcb42d8 56c9035 bcb42d8 56c9035 77fc5e6 56c9035 77fc5e6 56c9035 77fc5e6 56c9035 77fc5e6 fcf59c8 77fc5e6 fcf59c8 77fc5e6 fcf59c8 77fc5e6 fcf59c8 77fc5e6 fcf59c8 77fc5e6 fcf59c8 77fc5e6 fcf59c8 56c9035 fcf59c8 56c9035 fcf59c8 56c9035 fcf59c8 56c9035 fcf59c8 56c9035 fcf59c8 56c9035 fcf59c8 56c9035 fcf59c8 56c9035 fcf59c8 56c9035 fcf59c8 56c9035 fcf59c8 56c9035 fcf59c8 56c9035 fcf59c8 56c9035 fcf59c8 56c9035 fcf59c8 56c9035 fcf59c8 56c9035 377f363 56c9035 fcf59c8 56c9035 77fc5e6 56c9035 77fc5e6 56c9035 77fc5e6 56c9035 77fc5e6 56c9035 fcf59c8 56c9035 77fc5e6 56c9035 fcf59c8 77fc5e6 fcf59c8 bcb42d8 fcf59c8 bcb42d8 fcf59c8 bcb42d8 fcf59c8 77fc5e6 d9a631f 77fc5e6 d9a631f 77fc5e6 d9a631f 77fc5e6 d9a631f fcf59c8 77fc5e6 fcf59c8 bcb42d8 ae31090 | 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 | from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from paddleocr import PaddleOCR
from datetime import datetime
from rapidfuzz import fuzz
import cv2
import re
import numpy as np
import requests
app = FastAPI(title="OCR & Extraction Service")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Inisialisasi PaddleOCR
paddle_engine = PaddleOCR(
lang='id',
show_log=False,
use_angle_cls=False,
enable_mkldnn=True,
cpu_threads=2,
ocr_version="PP-OCRv4",
det_limit_side_len=640
)
SPACE_B_URL = "https://struklyai-clasify.hf.space/classify/"
SPACE_C_URL = "https://struklyai-clasify2.hf.space/classify/"
# ENGINE EKSTRAKSI (RULE-BASED + REGEX)
def clean(text):
return text.replace(" ", " ")
def clean_item_name(text):
text = re.sub(r'\d+[A-Z]?$', '', text).strip()
text = text.replace("'", "")
return text
MONTH_MAP = {
"jan": 1, "januari": 1,
"feb": 2, "februari": 2,
"mar": 3, "maret": 3,
"apr": 4, "april": 4, "ap": 4,
"mei": 5, "may": 5,
"jun": 6, "juni": 6,
"jul": 7, "juli": 7,
"aug": 8, "agu": 8, "agustus": 8,
"sep": 9, "september": 9,
"oct": 10, "okt": 10, "oktober": 10,
"nov": 11, "november": 11,
"dec": 12, "des": 12, "desember": 12,
}
def extract_transaction_date(raw_text: str):
raw_text = re.sub(r"\s+", " ", raw_text).strip()
current_year = datetime.now().year
def valid_year(y: int) -> bool:
return 2000 <= y <= current_year + 1
def make_date(d: int, m: int, y: int):
if y < 100:
y += 2000
if valid_year(y) and 1 <= m <= 12 and 1 <= d <= 31:
try:
return datetime(y, m, d)
except ValueError:
pass
return None
# yyyy-mm-ddTHH:MM[:SS]
hit = re.search(r'(\d{4})-(\d{2})-(\d{2})T', raw_text)
if hit:
dt = make_date(int(hit.group(3)), int(hit.group(2)), int(hit.group(1)))
if dt: return dt.strftime("%d-%m-%Y")
# yyyy[sep]mm[sep]dd
hit = re.search(r'(\d{4})[/\-.](\d{1,2})[/\-.](\d{1,2})', raw_text)
if hit:
dt = make_date(int(hit.group(3)), int(hit.group(2)), int(hit.group(1)))
if dt: return dt.strftime("%d-%m-%Y")
# HH[:.]MM[:SS] <space> dd[sep]mm[sep]yyyy/yy
hit = re.search(
r'\d{1,2}[:.]\d{2}(?::\d{2})?\s+(\d{1,2})[/\-.](\d{1,2})[/\-.](\d{2,4})',
raw_text
)
if hit:
dt = make_date(int(hit.group(1)), int(hit.group(2)), int(hit.group(3)))
if dt: return dt.strftime("%d-%m-%Y")
# dd[sep]Month[sep]yyyy/yy
for h in re.finditer(r'(\d{1,2})[/\-. ]([a-zA-Z]+)[/\-. ](\d{2,4})', raw_text, re.IGNORECASE):
candidate = h.group(2).lower()
if len(candidate) > 9:
continue
month_num = MONTH_MAP.get(candidate)
if month_num:
dt = make_date(int(h.group(1)), month_num, int(h.group(3)))
if dt: return dt.strftime("%d-%m-%Y")
# ddMonyyyy atau ddMonyy
for yr_pat in (r'(\d{4})', r'(\d{2})'):
hit = re.search(
rf'(\d{{1,2}})([a-zA-Z]{{2,}}){yr_pat}',
raw_text, re.IGNORECASE
)
if hit:
month_num = MONTH_MAP.get(hit.group(2).lower())
if month_num:
dt = make_date(int(hit.group(1)), month_num, int(hit.group(3)))
if dt: return dt.strftime("%d-%m-%Y")
# dd[sep]mm[sep]yyyy
for sep_pat in (r'[/\-.]', r'\s'):
hit = re.search(rf'(\d{{1,2}}){sep_pat}(\d{{1,2}}){sep_pat}(\d{{4}})', raw_text)
if hit:
dt = make_date(int(hit.group(1)), int(hit.group(2)), int(hit.group(3)))
if dt: return dt.strftime("%d-%m-%Y")
# yyyymmdd
hit = re.search(r'(?<!\d)(20\d{2})([01]\d)([0-3]\d)(?!\d)', raw_text)
if hit:
dt = make_date(int(hit.group(3)), int(hit.group(2)), int(hit.group(1)))
if dt: return dt.strftime("%d-%m-%Y")
# ddmmyyyy
hit = re.search(r'(?<!\d)([0-3]\d)([01]\d)(20\d{2})(?!\d)', raw_text)
if hit:
dt = make_date(int(hit.group(1)), int(hit.group(2)), int(hit.group(3)))
if dt: return dt.strftime("%d-%m-%Y")
# dd[sep]mm[sep]yy
for sep in ('-', '/', '.', ' '):
esc = re.escape(sep)
hit = re.search(
rf'(\d{{1,2}}){esc}(\d{{1,2}}){esc}(\d{{2}})(?!\d{{2}}{esc})',
raw_text
)
if hit:
dt = make_date(int(hit.group(1)), int(hit.group(2)), int(hit.group(3)))
if dt: return dt.strftime("%d-%m-%Y")
# ddmmyy
hit = re.search(r'(?<!\d)([0-3]\d)([01]\d)(\d{2})(?!\d)', raw_text)
if hit:
dt = make_date(int(hit.group(1)), int(hit.group(2)), int(hit.group(3)))
if dt: return dt.strftime("%d-%m-%Y")
return None
def extract_number(line):
line = line.upper().replace("RP", "")
match = re.search(r'\d{1,3}(?:[.,]\d{3})+', line)
return match.group() if match else None
def has_money(line):
return bool(extract_number(line))
def is_noise(line):
upper = line.upper().strip()
noise_keywords = [
"TOTAL", "SUBTOTAL", "CASH", "KEMBALI", "CHANGE", "BAYAR", "PAID",
"ITEM", "QTY", "TERIMA", "KASIH", "THANK", "PELANGGAN",
"STAFF", "KASSA", "NPWP", "TRANS", "DELIVERY",
"DISCOUNT", "DISC", "ROUNDED", "DEBIT", "CREDIT",
"PPN", "DPP", "TUNAI", "HEMAT",
"UNBOXING", "COMPLAIN", "VIDEO",
"WWW.", "HTTP",
"CASHIER", "MOHON"
]
address_keywords = [
"JL", "JLN", "JALAN", "RAYA", "KEL", "KEC", "KAB",
"KOTA", "RT", "RW","BARAT", "TIMUR",
"SELATAN", "UTARA", "TENGAH"
]
promo_keywords = [
"PT ", "/PT", "CV ", "PROMO", "VOUCHER", "MEMBER"
]
if any(k in upper for k in noise_keywords):
return True
if any(k in upper for k in address_keywords):
return True
if any(k in upper for k in promo_keywords):
return True
if re.fullmatch(r'[\d.,:=-]+', upper):
return True
if re.search(r'\{?\d+\}?X\d+', upper.replace(" ", "")):
return True
if re.search(r'\d+\s*X\s*@?', upper):
return True
if re.search(r'\bRP\b', upper):
return True
return False
def is_product_like(line):
return (
bool(re.search(r'\d+\s*(PCS|BKS|BTL|@)', line.upper())) or
bool(re.search(r'\d{1,3}[.,]\d{3}', line))
)
def is_noise_merc(line):
upper = line.upper().strip()
noise_keywords = [
"TOTAL", "CASH", "KEMBALI", "CHANGE", "BAYAR", "PAID",
"ITEM", "QTY", "TERIMA", "KASIH", "THANK",
"RUKO", "PELANGGAN", "STAFF", "KASSA",
"NPWP", "HP", "TRANS", "BISA DELIVERY"
]
if any(k in upper for k in noise_keywords):
return True
if re.fullmatch(r'[\d.,:()\-]+', upper):
return True
if re.fullmatch(r'\d+\w*@', upper.replace(" ", "")):
return True
if "." in line and len(line.split()) == 1:
return True
if re.search(r'^[A-Z0-9]{5,}$', upper) and any(c.isdigit() for c in upper):
return True
return False
def detect_merchant(lines):
for line in lines[:4]:
line = line.strip("= ").strip()
if not line:
continue
if is_noise_merc(line):
continue
# skip line yang mirip product / harga
if is_product_like(line):
continue
# skip line dominan angka
if any(c.isdigit() for c in line) and len(line) < 8:
continue
return line
return "Tidak Terdeteksi"
def normalize(line):
return re.sub(r"\s+", " ", line).strip()
def is_noise_items(line):
NOISE_KEYWORDS = {
"TOTAL", "SUBTOTAL", "CASH", "KEMBALI", "CHANGE", "BAYAR", "PAID",
"ITEM", "QTY", "TERIMA", "KASIH", "THANK", "PELANGGAN",
"STAFF", "KASSA", "NPWP", "TRANS", "DELIVERY", "TT4L",
"DISCOUNT", "DISC", "ROUNDED", "DEBIT", "CREDIT", "BTKP",
"PPN", "DPP", "TUNAI", "HEMAT", "TIMUR", "BARAT", "BKP",
"UNBOXING", "COMPLAIN", "VIDEO", "UTARA", "SELATAN",
"WWW", "HTTP", "CASHIER", "MOHON", "JL", "J1", "JALAN",
"RAYA", "KEL", "KEC", "KAB", "KOTA", "RT", "RW",
"PT", "/PT", "CV", "PROMO", "VOUCHER", "MEMBER",
"TAGIHAN", "TEMPAT", "WAKTU", "CHECK", "PAYMENT",
"CLOSED", "SARAN", "CUSTOMER", "SERVICE",
"POTONGAN", "PEMBAYARAN", "JUMLAH BAYAR"
}
line = normalize(line)
upper = line.upper()
if not line:
return True
if re.fullmatch(r'[\d.,:;=\-+@{}xX()/ ]+', line):
return True
if re.search(r'\bRP\b', upper):
return True
if any(k in upper for k in NOISE_KEYWORDS):
return True
if "WWW" in upper or "HTTP" in upper:
return True
if re.search(r'\d{1,2}[/-]\d{1,2}[/-]\d{2,4}', line):
return True
if re.search(r'\d{1,2}:\d{2}', line):
return True
return False
def looks_like_price(line):
line = normalize(line).upper()
if re.search(r'RP\s?[\d.,]+', line):
return True
if re.fullmatch(r'[\d.,]{3,}', line):
return True
return False
def looks_like_qty_price(line):
line = normalize(line).upper().replace(" ", "")
patterns = [
r'^\{?\d+\}?X',
r'^\d+[.,]?\d*X@',
r'^\d+(PCS|BTL|BKS)@?',
]
return any(re.search(p, line) for p in patterns)
def is_item_candidate(line):
line = normalize(line)
if is_noise_items(line):
return False
letters = sum(c.isalpha() for c in line)
if letters < 3:
return False\
if re.fullmatch(r'[A-Z0-9\-]{8,}', line.upper()):
return False
return True
def looks_like_phone(line):
digits = re.sub(r'\D', '', line)
lowered = line.lower()
return (
len(digits) >= 9 and
(
digits.startswith('08') or
digits.startswith('62') or
'telp' in lowered or
'phone' in lowered or
'hp' in lowered
)
)
def clean_item(line):
line = normalize(line)
line = re.sub(r'^\{?\d+\}?[Xx]\s*@?[\d.,]*', '', line)
line = re.sub(r'^\d+(PCS|BTL|BKS)@?', '', line, flags=re.I)
return line.strip(" -=@")
def extract_items(lines):
lines = [normalize(x) for x in lines if normalize(x) and not looks_like_phone(normalize(x))]
lines = lines[3:]
result = []
i = 0
while i < len(lines):
line = lines[i]
# qty+item same line
if looks_like_qty_price(line):
item = clean_item(line)
if is_item_candidate(item):
result.append(item)
i += 1
continue
# item followed by price/qty
if is_item_candidate(line) and not looks_like_phone(line):
next_lines = lines[i+1:i+4]
if any(looks_like_price(x) or looks_like_qty_price(x) for x in next_lines):
result.append(line)
i += 1
continue
# qty line followed by item
if looks_like_qty_price(line) or re.match(r'^\d+[Xx]', line):
next_lines = lines[i+1:i+3]
for nxt in next_lines:
if is_item_candidate(nxt):
result.append(nxt)
break
i += 1
seen = set()
final = []
for x in result:
key = x.upper()
if key not in seen:
seen.add(key)
final.append(x)
final = [item.lstrip('0123456789 ') for item in final]
return final
def extract_number(text):
nums = re.findall(r'-?\d[\d.,]*', text)
values = []
for n in nums:
digits = re.sub(r'\D', '', n)
if len(digits) > 7:
continue
clean = re.sub(r'[.,]', '', n)
clean = clean.replace("-", "")
if clean.isdigit():
value = int(clean)
if 100 <= value <= 50000000:
values.append(value)
if not values:
return None
return max(values)
def detect_total(lines):
rules = [
(r"^TOTAL[: ]*$", 100),
(r"\bTOTAL\s*BAYAR\b", 95),
(r"\bGRAND\s*TOTAL\b", 95),
(r"\bPEMBAYARAN\b", 90),
(r"\bSUB\s*TOTAL\b", 50),
]
ignore_keywords = [
"HEMAT", "DISCOUNT", "PPN", "DPP",
"BKP", "POT", "BTKP", "TELP",
"CUSTOMER", "NPWP",
]
stop_keywords = [
"KEMBALI", "CHANGE",
]
candidates = []
for i, line in enumerate(lines):
up = line.upper().strip()
if any(x in up for x in ignore_keywords):
continue
for pattern, score in rules:
if re.search(pattern, up):
for j in range(i, min(i + 5, len(lines))):
nxt = lines[j].upper().strip()
if any(x in nxt for x in stop_keywords):
break
num = extract_number(lines[j])
if num:
distance_penalty = (j - i) * 5
final_score = score - distance_penalty
candidates.append(
(final_score, num)
)
if not candidates:
return "0"
candidates.sort(reverse=True)
return str(candidates[0][1])
def extract_receipt(text):
text = clean(text)
lines = [l.strip() for l in text.split("\n") if l.strip()]
return {
"merchant": detect_merchant(lines),
"items": extract_items(lines),
"total": detect_total(lines)
}
# API ENDPOINTS
@app.get("/")
def home():
return {"status": "Optima Team - OCR API Aktif :D !"}
@app.post("/scan-ocr/")
async def proses_gambar_paddle(file: UploadFile = File(...)):
try:
contents = await file.read()
nparr = np.frombuffer(contents, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
result = paddle_engine.ocr(img)
teks_terbaca = []
if result and result[0]:
for baris in result[0]:
teks_terbaca.append(baris[1][0])
ocr_mentah = "\n".join(teks_terbaca)
date = extract_transaction_date(ocr_mentah)
hasil_ekstraksi = extract_receipt(ocr_mentah)
merchant = hasil_ekstraksi["merchant"]
items_list = hasil_ekstraksi["items"]
total_str = re.sub(r'[^\d]', '', hasil_ekstraksi["total"])
total = int(total_str) if total_str else 0
class_id = None
class_name = "Tidak Ditemukan"
confidence = 0.0
if items_list:
target_spaces = [SPACE_B_URL, SPACE_C_URL]
berhasil_klasifikasi = False
for url in target_spaces:
try:
response = requests.post(url, json={"items": items_list}, timeout=15)
if response.status_code == 200:
data = response.json()
class_id = data.get("class_id")
class_name = data.get("category_name")
confidence = data.get("confidence")
berhasil_klasifikasi = True
break # break loop jika respons 200
else:
print(f"Gagal dari {url}, status: {response.status_code}. Beralih ke Next Space")
except requests.exceptions.RequestException as e:
print(f"Koneksi ke {url} gagal ({e}). Beralih ke Next Space")
if not berhasil_klasifikasi:
print("Semua Space AI gagal dihubungi.")
class_name = "Error AI (Semua Server Down/Limit)"
return {
"sukses": True,
"ocr_mentah": ocr_mentah,
"date": date,
"items": items_list,
"merchant": merchant,
"total": total,
"classes": class_id,
"category_name": class_name,
"confidence": confidence
}
except Exception as e:
return JSONResponse(status_code=500, content={"sukses": False, "pesan": str(e)})
@app.get("/ping")
async def antisleep():
return {"success": True, "message": "Server OCR aktif"} |