aiinfinite latest code
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
.git
|
||||
.gitignore
|
||||
__pycache__
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
.env
|
||||
.venv
|
||||
venv
|
||||
uploads/*
|
||||
!uploads/.gitkeep
|
||||
reference_unused_modules
|
||||
.vscode
|
||||
.idea
|
||||
*.log
|
||||
@@ -0,0 +1,9 @@
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.env
|
||||
uploads/*
|
||||
!uploads/.gitkeep
|
||||
reference_unused_modules/
|
||||
.vscode/
|
||||
.idea/
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
# Use an official lightweight Python image
|
||||
FROM python:3.11-slim
|
||||
|
||||
# Set environment variables
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PORT=5000
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Install system dependencies
|
||||
# - poppler-utils: required by pdf2image for PDF processing
|
||||
# - libgl1 & libglib2.0-0: required for OpenCV and image operations
|
||||
# - curl: for container healthchecks
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
poppler-utils \
|
||||
libgl1 \
|
||||
libglib2.0-0 \
|
||||
curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Python dependencies first (leverages Docker layer cache)
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir --upgrade pip && \
|
||||
pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy application source code
|
||||
COPY . .
|
||||
|
||||
# Ensure uploads directory exists
|
||||
RUN mkdir -p /app/uploads
|
||||
|
||||
# Expose port
|
||||
EXPOSE 5000
|
||||
|
||||
# Run with Gunicorn (production WSGI server with timeout suitable for multi-page OCR)
|
||||
CMD ["gunicorn", "--bind", "0.0.0.0:5000", "--workers", "3", "--threads", "2", "--timeout", "180", "app:app"]
|
||||
Binary file not shown.
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"_comment": "Human-verified batch corrections for OCR misreads and pen mark occlusions",
|
||||
"2525CG2": "25255CG2",
|
||||
"2525SCG2": "25255CG2",
|
||||
"25255C62": "25255CG2"
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
"""
|
||||
Consistency Checker — Math-based validation of extracted invoice data.
|
||||
|
||||
Checks that extracted numbers are internally consistent:
|
||||
- Per-item : GST_AMT ≈ Value × Gst% / 100
|
||||
- Per-item : cgst_amount + sgst_amount + igst_amount ≈ GST_AMT
|
||||
- Invoice : sum(item GST_AMTs) ≈ total_gst_amount
|
||||
- Invoice : sum(item Values) ≈ invoice_amount − total_gst_amount (rough check)
|
||||
|
||||
Does NOT fix values — only adds a '_needs_review' flag and a
|
||||
'_review_reasons' list to suspicious items/invoice so the caller
|
||||
(or a human) knows exactly which rows to double-check.
|
||||
|
||||
Zero extra API calls. Pure Python maths.
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from decimal import Decimal, ROUND_HALF_UP
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Helpers
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
def _f(value: Any) -> Optional[float]:
|
||||
"""Safe float conversion; returns None on failure."""
|
||||
if value is None or value == '':
|
||||
return None
|
||||
try:
|
||||
return float(str(value).replace(',', '').replace('₹', '').strip())
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def _decimal_round(value: float, decimals: int = 2) -> float:
|
||||
"""Round using Decimal with ROUND_HALF_UP (financial rounding)."""
|
||||
d = Decimal(str(value))
|
||||
quantizer = Decimal('0.01') if decimals == 2 else Decimal(10) ** -decimals
|
||||
return float(d.quantize(quantizer, rounding=ROUND_HALF_UP))
|
||||
|
||||
|
||||
def _close(a: float, b: float, tol: float = 1.0) -> bool:
|
||||
"""True if |a - b| <= tol."""
|
||||
return abs(a - b) <= tol
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Per-item checks
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
def _check_item(item: Dict[str, Any], idx: int) -> List[str]:
|
||||
"""
|
||||
Return a list of reason strings for a suspicious item.
|
||||
Empty list means the item passes all checks.
|
||||
"""
|
||||
reasons = []
|
||||
|
||||
gst_amt = _f(item.get('GST_AMT'))
|
||||
gst_pct = _f(item.get('Gst%'))
|
||||
value = _f(item.get('Value')) or _f(item.get('taxable_value')) or _f(item.get('total_price'))
|
||||
cgst_amt = _f(item.get('cgst_amount'))
|
||||
sgst_amt = _f(item.get('sgst_amount'))
|
||||
igst_amt = _f(item.get('igst_amount'))
|
||||
cgst_rate = _f(item.get('cgst_rate'))
|
||||
sgst_rate = _f(item.get('sgst_rate'))
|
||||
qty = _f(item.get('quantity')) if not isinstance(item.get('quantity'), str) else None
|
||||
unit_price = _f(item.get('unit_price'))
|
||||
total_price = _f(item.get('total_price'))
|
||||
|
||||
# Check 1: GST_AMT vs taxable_value × Gst% (DISCOUNT-AWARE)
|
||||
# CRITICAL: GST is calculated on taxable_value (after discount), NOT on Value (before discount)
|
||||
if gst_amt is not None and value is not None and gst_pct is not None:
|
||||
# Check if item has a discount percentage
|
||||
discount_pct = _f(item.get('Discount'))
|
||||
if discount_pct is not None and discount_pct > 0:
|
||||
# Apply discount: taxable_value = Value × (1 - Discount/100)
|
||||
taxable_value = _decimal_round(value * (1 - discount_pct / 100))
|
||||
else:
|
||||
# No discount, taxable_value = Value
|
||||
taxable_value = value
|
||||
|
||||
expected_gst = _decimal_round(taxable_value * gst_pct / 100)
|
||||
if not _close(gst_amt, expected_gst, tol=1.0):
|
||||
reasons.append(
|
||||
f"GST_AMT mismatch: extracted={gst_amt}, "
|
||||
f"expected={expected_gst} (taxable_value={taxable_value} × Gst%={gst_pct}/100, "
|
||||
f"Value={value}, Discount={discount_pct}%)"
|
||||
)
|
||||
|
||||
# Check 2: CGST + SGST + IGST ≈ GST_AMT
|
||||
if gst_amt is not None:
|
||||
components = []
|
||||
if cgst_amt is not None:
|
||||
components.append(cgst_amt)
|
||||
if sgst_amt is not None:
|
||||
components.append(sgst_amt)
|
||||
if igst_amt is not None:
|
||||
components.append(igst_amt)
|
||||
if components:
|
||||
component_sum = round(sum(components), 2)
|
||||
if not _close(gst_amt, component_sum, tol=0.5):
|
||||
reasons.append(
|
||||
f"GST component sum mismatch: CGST({cgst_amt})+SGST({sgst_amt})"
|
||||
f"+IGST({igst_amt})={component_sum} ≠ GST_AMT={gst_amt}"
|
||||
)
|
||||
|
||||
# Check 3: CGST rate = SGST rate (intra-state rule)
|
||||
if cgst_rate is not None and sgst_rate is not None:
|
||||
if not _close(cgst_rate, sgst_rate, tol=0.01):
|
||||
reasons.append(
|
||||
f"CGST rate ({cgst_rate}%) ≠ SGST rate ({sgst_rate}%) — "
|
||||
f"intra-state split should be equal"
|
||||
)
|
||||
|
||||
# Check 4: Gst% = CGST rate + SGST rate (when both exist)
|
||||
if gst_pct is not None and cgst_rate is not None and sgst_rate is not None:
|
||||
expected_rate = round(cgst_rate + sgst_rate, 2)
|
||||
if not _close(gst_pct, expected_rate, tol=0.01):
|
||||
reasons.append(
|
||||
f"Gst% ({gst_pct}) ≠ CGST({cgst_rate})+SGST({sgst_rate})={expected_rate}"
|
||||
)
|
||||
|
||||
# Check 5: qty × unit_price ≈ total_price (when all three present)
|
||||
if qty is not None and unit_price is not None and total_price is not None:
|
||||
expected_total = round(qty * unit_price, 2)
|
||||
# Allow 2% tolerance for rounding on large quantities
|
||||
tol = max(1.0, round(expected_total * 0.02, 2))
|
||||
if not _close(total_price, expected_total, tol=tol):
|
||||
reasons.append(
|
||||
f"qty×unit_price mismatch: {qty}×{unit_price}={expected_total} "
|
||||
f"≠ total_price={total_price} (tol={tol})"
|
||||
)
|
||||
|
||||
return reasons
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Invoice-level checks
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
def _check_invoice_totals(data: Dict[str, Any]) -> List[str]:
|
||||
"""Return invoice-level inconsistency reasons."""
|
||||
reasons = []
|
||||
|
||||
items = data.get('items', [])
|
||||
total_gst = _f(data.get('total_gst_amount'))
|
||||
total_cgst = _f(data.get('total_cgst_amount'))
|
||||
total_sgst = _f(data.get('total_sgst_amount'))
|
||||
total_igst = _f(data.get('total_igst_amount'))
|
||||
invoice_amt = _f(data.get('invoice_amount'))
|
||||
|
||||
# Check 1: sum of item GST_AMTs ≈ total_gst_amount
|
||||
if total_gst is not None and items:
|
||||
item_gst_values = [_f(i.get('GST_AMT')) for i in items]
|
||||
if all(v is not None for v in item_gst_values):
|
||||
item_gst_sum = round(sum(item_gst_values), 2)
|
||||
if not _close(item_gst_sum, total_gst, tol=2.0):
|
||||
reasons.append(
|
||||
f"Invoice total_gst_amount={total_gst} ≠ "
|
||||
f"sum of item GST_AMTs={item_gst_sum} "
|
||||
f"(diff={round(abs(item_gst_sum - total_gst), 2)})"
|
||||
)
|
||||
|
||||
# Check 2: total_cgst + total_sgst + total_igst ≈ total_gst_amount
|
||||
if total_gst is not None:
|
||||
components = []
|
||||
if total_cgst is not None:
|
||||
components.append(total_cgst)
|
||||
if total_sgst is not None:
|
||||
components.append(total_sgst)
|
||||
if total_igst is not None:
|
||||
components.append(total_igst)
|
||||
if components:
|
||||
component_sum = round(sum(components), 2)
|
||||
if not _close(total_gst, component_sum, tol=1.0):
|
||||
reasons.append(
|
||||
f"total_gst_amount={total_gst} ≠ "
|
||||
f"CGST({total_cgst})+SGST({total_sgst})+IGST({total_igst})={component_sum}"
|
||||
)
|
||||
|
||||
# Check 3: CRITICAL - Discount-aware invoice total validation
|
||||
# Formula: Gross - Discount + GST = Grand Total
|
||||
# NOT: Gross + GST = Grand Total (this ignores discount!)
|
||||
if invoice_amt is not None and total_gst is not None and items:
|
||||
# Sum gross item Values (before discount)
|
||||
item_values = [_f(i.get('Value')) for i in items]
|
||||
if all(v is not None for v in item_values):
|
||||
gross_sum = round(sum(item_values), 2)
|
||||
|
||||
# Get invoice-level discount OR calculate from items
|
||||
total_discount = _f(data.get('total_discount_amount'))
|
||||
if total_discount is None or total_discount == 0:
|
||||
# Calculate from item-level discounts
|
||||
item_discounts = []
|
||||
for item in items:
|
||||
val = _f(item.get('Value'))
|
||||
disc_pct = _f(item.get('Discount'))
|
||||
if val and disc_pct and disc_pct > 0:
|
||||
item_discounts.append(_decimal_round(val * disc_pct / 100))
|
||||
if item_discounts:
|
||||
total_discount = round(sum(item_discounts), 2)
|
||||
else:
|
||||
total_discount = 0.0
|
||||
|
||||
# Calculate expected: Gross - Discount + GST
|
||||
taxable_sum = round(gross_sum - total_discount, 2)
|
||||
expected_invoice = round(taxable_sum + total_gst, 2)
|
||||
|
||||
# 2% tolerance — invoices sometimes have rounding, extra charges etc.
|
||||
tol = max(5.0, round(invoice_amt * 0.02, 2))
|
||||
if not _close(invoice_amt, expected_invoice, tol=tol):
|
||||
reasons.append(
|
||||
f"invoice_amount={invoice_amt} ≠ "
|
||||
f"(Gross={gross_sum} - Discount={total_discount} + GST={total_gst})={expected_invoice} "
|
||||
f"(diff={round(abs(invoice_amt - expected_invoice), 2)}, tol={tol})"
|
||||
)
|
||||
|
||||
return reasons
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Top-level: run all checks and annotate data
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
def run_consistency_checks(data: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
||||
"""
|
||||
Run all consistency checks on extracted invoice data.
|
||||
|
||||
Annotates:
|
||||
- Suspicious items get '_needs_review': True, '_review_reasons': [...]
|
||||
- Clean items get '_needs_review': False
|
||||
- Invoice-level issues stored in data['_invoice_review_reasons']
|
||||
|
||||
Returns:
|
||||
(annotated_data, summary_dict)
|
||||
|
||||
The summary_dict has:
|
||||
{
|
||||
'items_flagged': int,
|
||||
'items_clean': int,
|
||||
'invoice_issues': [...],
|
||||
'has_issues': bool
|
||||
}
|
||||
"""
|
||||
if not data or not isinstance(data, dict):
|
||||
return data, {'items_flagged': 0, 'items_clean': 0,
|
||||
'invoice_issues': [], 'has_issues': False}
|
||||
|
||||
print("\n" + "=" * 70)
|
||||
print("CONSISTENCY CHECK")
|
||||
print("=" * 70)
|
||||
|
||||
items_flagged = 0
|
||||
items_clean = 0
|
||||
|
||||
# ── Per-item checks ───────────────────────────────────────────────────────
|
||||
for idx, item in enumerate(data.get('items', []), start=1):
|
||||
reasons = _check_item(item, idx)
|
||||
if reasons:
|
||||
item['_needs_review'] = True
|
||||
item['_review_reasons'] = reasons
|
||||
items_flagged += 1
|
||||
desc = (item.get('description') or '')[:40]
|
||||
batch = item.get('Batch') or 'N/A'
|
||||
print(f" ⚠️ Item {idx} [{desc}] Batch={batch}:")
|
||||
for r in reasons:
|
||||
print(f" → {r}")
|
||||
else:
|
||||
item['_needs_review'] = False
|
||||
items_clean += 1
|
||||
|
||||
# ── Invoice-level checks ──────────────────────────────────────────────────
|
||||
invoice_issues = _check_invoice_totals(data)
|
||||
if invoice_issues:
|
||||
data['_invoice_review_reasons'] = invoice_issues
|
||||
print(f"\n ⚠️ Invoice-level issues:")
|
||||
for issue in invoice_issues:
|
||||
print(f" → {issue}")
|
||||
else:
|
||||
data['_invoice_review_reasons'] = []
|
||||
|
||||
has_issues = items_flagged > 0 or len(invoice_issues) > 0
|
||||
|
||||
print(f"\n Items checked : {items_flagged + items_clean}")
|
||||
print(f" Items flagged : {items_flagged}")
|
||||
print(f" Items clean : {items_clean}")
|
||||
print(f" Invoice issues: {len(invoice_issues)}")
|
||||
print("=" * 70 + "\n")
|
||||
|
||||
summary = {
|
||||
'items_flagged': items_flagged,
|
||||
'items_clean': items_clean,
|
||||
'invoice_issues': invoice_issues,
|
||||
'has_issues': has_issues,
|
||||
}
|
||||
|
||||
return data, summary
|
||||
+14355
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,364 @@
|
||||
"""
|
||||
Free Item Splitter - Splits items with free quantities into separate records
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional, Tuple
|
||||
import copy
|
||||
import re
|
||||
|
||||
try:
|
||||
from langsmith import traceable
|
||||
except ImportError:
|
||||
def traceable(*args, **kwargs):
|
||||
def decorator(fn):
|
||||
return fn
|
||||
return decorator
|
||||
|
||||
|
||||
def _to_float(val: Any) -> Optional[float]:
|
||||
"""Safely convert any value (int, float, string like '2', '2.0', ' 2 ') to float."""
|
||||
if val is None:
|
||||
return None
|
||||
if isinstance(val, (int, float)):
|
||||
return float(val)
|
||||
try:
|
||||
cleaned = re.sub(r'[^\d.]', '', str(val)).strip()
|
||||
return float(cleaned) if cleaned else None
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def _format_qty(val: Any) -> Any:
|
||||
"""Format quantity: integer if whole number (e.g. 20 instead of 20.0), else float."""
|
||||
if val is None:
|
||||
return 0
|
||||
if isinstance(val, (int, float)):
|
||||
if float(val).is_integer():
|
||||
return int(val)
|
||||
return round(float(val), 2)
|
||||
num = _to_float(val)
|
||||
if num is not None:
|
||||
if num.is_integer():
|
||||
return int(num)
|
||||
return round(num, 2)
|
||||
return val
|
||||
|
||||
|
||||
def _parse_plus_qty(qty_val: Any) -> Optional[Tuple[float, float]]:
|
||||
"""Parse '20+2' or '20 + 2' into (paid=20.0, free=2.0)."""
|
||||
if not qty_val:
|
||||
return None
|
||||
s = str(qty_val).strip()
|
||||
if '+' not in s:
|
||||
return None
|
||||
parts = s.split('+')
|
||||
if len(parts) >= 2:
|
||||
# OCR common letter replacements in numbers
|
||||
p1 = parts[0].strip().replace('S', '5').replace('s', '5').replace('O', '0').replace('o', '0')
|
||||
p2 = parts[1].strip().replace('S', '5').replace('s', '5').replace('O', '0').replace('o', '0')
|
||||
n1 = _to_float(p1)
|
||||
n2 = _to_float(p2)
|
||||
if n1 is not None and n2 is not None:
|
||||
return n1, n2
|
||||
return None
|
||||
|
||||
|
||||
def _extract_free_from_description(desc: str) -> Optional[Tuple[Optional[float], float]]:
|
||||
"""
|
||||
Check if description contains free patterns like:
|
||||
- '10+1 FREE' or '10+2 SCHEME' or '(10+1)'
|
||||
- 'FREE: 2' or 'FREE QTY: 2' or '2 FREE'
|
||||
- 'SCHEME 10+1' or 'BONUS: 1'
|
||||
Returns (paid_qty_from_desc, free_qty) or None.
|
||||
Never triggers on medicine dosage/composition like '500+125 MG'.
|
||||
"""
|
||||
if not desc or not isinstance(desc, str):
|
||||
return None
|
||||
|
||||
# Skip dosage/strength expressions like 500+125 MG, 325 + 37.5 MG, 5% + 0.9%
|
||||
if re.search(r'\d+\s*\+\s*\d+\s*(?:mg|ml|gm|mcg|%|iu|tab|cap|vial|pcs)\b', desc, re.IGNORECASE):
|
||||
return None
|
||||
|
||||
# Pattern: 10+1 FREE or 10+2 SCHEME or 10+1 BONUS
|
||||
m_plus_explicit = re.search(
|
||||
r'\(?\s*(\d+(?:\.\d+)?)\s*\+\s*(\d+(?:\.\d+)?)\s*(?:FREE|SCHEME|SCH|BONUS|OFFER)\b\)?',
|
||||
desc,
|
||||
re.IGNORECASE
|
||||
)
|
||||
if m_plus_explicit:
|
||||
p1 = _to_float(m_plus_explicit.group(1))
|
||||
p2 = _to_float(m_plus_explicit.group(2))
|
||||
if p1 is not None and p2 is not None and p2 > 0:
|
||||
return p1, p2
|
||||
|
||||
# Pattern in brackets: e.g. (10+1) or (20+2) without dosage units
|
||||
m_plus_bracket = re.search(r'\(\s*(\d+(?:\.\d+)?)\s*\+\s*(\d+(?:\.\d+)?)\s*\)', desc, re.IGNORECASE)
|
||||
if m_plus_bracket:
|
||||
p1 = _to_float(m_plus_bracket.group(1))
|
||||
p2 = _to_float(m_plus_bracket.group(2))
|
||||
if p1 is not None and p2 is not None and p2 > 0:
|
||||
return p1, p2
|
||||
|
||||
# Pattern: FREE: 2 or FREE QTY: 2 or SCHEME: 1
|
||||
m_free = re.search(r'(?:FREE|SCHEME|BONUS|F\.?QTY|DISC\.?\s*QTY)[:\s=-]+(\d+(?:\.\d+)?)\b', desc, re.IGNORECASE)
|
||||
if m_free:
|
||||
f_qty = _to_float(m_free.group(1))
|
||||
if f_qty is not None and f_qty > 0:
|
||||
return None, f_qty
|
||||
|
||||
# Pattern: 2 FREE or 1 FREE
|
||||
m_trail = re.search(r'(?:^|[\s(,])(\d+(?:\.\d+)?)\s*(?:FREE|SCHEME|BONUS)\b', desc, re.IGNORECASE)
|
||||
if m_trail:
|
||||
f_qty = _to_float(m_trail.group(1))
|
||||
if f_qty is not None and f_qty > 0:
|
||||
return None, f_qty
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _extract_free_quantity(item: Dict[str, Any]) -> Optional[float]:
|
||||
"""Extract free quantity from any known free/scheme/bonus field."""
|
||||
for k in (
|
||||
'free_quantity', 'free_qty', 'free', 'Free', 'FREE',
|
||||
'scheme_qty', 'scheme_quantity', 'disc_qty', 'discount_qty',
|
||||
'bonus_qty', 'bonus', 'f_qty', 'f_quantity'
|
||||
):
|
||||
v = item.get(k)
|
||||
if v is not None:
|
||||
f = _to_float(v)
|
||||
if f is not None and f > 0:
|
||||
return f
|
||||
return None
|
||||
|
||||
|
||||
def create_item_record(base_item: Dict[str, Any], new_qty: Any, is_free: bool) -> Dict[str, Any]:
|
||||
"""
|
||||
Create an item record (paid or free).
|
||||
ALL DATA SAME as base item, except:
|
||||
- quantity = new_qty (formatted as int if whole number)
|
||||
- free_item = 1 if is_free else 0
|
||||
- free_item_yn = "1" if is_free else "0"
|
||||
"""
|
||||
new_item = copy.deepcopy(base_item)
|
||||
new_item['quantity'] = _format_qty(new_qty)
|
||||
new_item['free_item'] = 1 if is_free else 0
|
||||
new_item['free_item_yn'] = "1" if is_free else "0"
|
||||
for k in (
|
||||
'free_quantity', 'free_qty', 'free', 'Free', 'FREE',
|
||||
'scheme_qty', 'scheme_quantity', 'disc_qty', 'discount_qty',
|
||||
'bonus_qty', 'bonus', 'f_qty', 'f_quantity'
|
||||
):
|
||||
new_item.pop(k, None)
|
||||
return new_item
|
||||
|
||||
|
||||
# Backward-compatible alias
|
||||
create_proportional_item = create_item_record
|
||||
|
||||
|
||||
@traceable(name="split_free_items", tags=["items", "splitting"])
|
||||
def split_free_items(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Apply free item splitting and non-repeatable conditions:
|
||||
1. When free item is mentioned:
|
||||
Show repeated:
|
||||
- Paid item: quantity=paid_qty, free_item=0, free_item_yn="0"
|
||||
- Free item: quantity=free_qty mentioned (or 1), free_item=1, free_item_yn="1"
|
||||
and all other fields EXACTLY as they are from the item above!
|
||||
2. When free item is not mentioned:
|
||||
- Exactly ONE record: free_item=0, free_item_yn="0"
|
||||
- That item CANNOT be repeatable (strictly deduplicated and never repeated).
|
||||
"""
|
||||
items = data.get('items', [])
|
||||
if not items:
|
||||
return data
|
||||
|
||||
def _norm_desc(d: Any) -> str:
|
||||
return re.sub(r'[^a-z0-9]', '', str(d or '').lower())
|
||||
|
||||
def _is_empty(v: Any) -> bool:
|
||||
if v is None:
|
||||
return True
|
||||
return str(v).strip().lower() in ('', 'none', 'null', 'n/a', '?', '-', 'undefined')
|
||||
|
||||
def _is_free_flagged(it: Dict[str, Any]) -> bool:
|
||||
return str(it.get('free_item_yn')) == "1" or str(it.get('free_item')) == "1"
|
||||
|
||||
# ── PRE-PASS: Merge two-row free item format ──────────────────────────────
|
||||
merged_items = []
|
||||
skip_next = False
|
||||
|
||||
for i, item in enumerate(items):
|
||||
if skip_next:
|
||||
skip_next = False
|
||||
continue
|
||||
|
||||
qty = item.get('quantity')
|
||||
qty_num = _to_float(qty) if not (isinstance(qty, str) and '+' in str(qty)) else None
|
||||
is_zero_qty = (qty_num is not None and qty_num == 0)
|
||||
is_free_flag = _is_free_flagged(item)
|
||||
|
||||
if is_zero_qty and is_free_flag and i + 1 < len(items):
|
||||
next_item = items[i + 1]
|
||||
next_desc = _norm_desc(next_item.get('description'))
|
||||
this_desc = _norm_desc(item.get('description'))
|
||||
|
||||
if next_desc and this_desc and next_desc == this_desc:
|
||||
next_qty_num = _to_float(next_item.get('quantity'))
|
||||
if next_qty_num and next_qty_num > 0:
|
||||
free_qty_value = _extract_free_quantity(item) or _to_float(item.get('quantity'))
|
||||
if not free_qty_value or free_qty_value <= 0:
|
||||
skip_next = False
|
||||
continue
|
||||
merged = copy.deepcopy(next_item)
|
||||
merged['free_quantity'] = free_qty_value
|
||||
merged['free_item'] = 1
|
||||
merged['free_item_yn'] = "1"
|
||||
merged_items.append(merged)
|
||||
skip_next = True
|
||||
continue
|
||||
|
||||
# Drop standalone zero-quantity ghost records (qty=0, no free_quantity and not free)
|
||||
if is_zero_qty and not _extract_free_quantity(item) and not is_free_flag:
|
||||
continue
|
||||
|
||||
merged_items.append(item)
|
||||
|
||||
items = merged_items
|
||||
|
||||
# ── SPLIT PASS: Free item mentioned repeats with free_item=1 and fields as above ──
|
||||
new_items: List[Dict[str, Any]] = []
|
||||
|
||||
for item in items:
|
||||
qty_raw = item.get('quantity')
|
||||
free_qty_num = _extract_free_quantity(item)
|
||||
desc = item.get('description') or ''
|
||||
is_free_flag = _is_free_flagged(item)
|
||||
|
||||
# Case 1: "20+2" format in quantity column
|
||||
plus_parsed = _parse_plus_qty(qty_raw)
|
||||
if plus_parsed:
|
||||
paid_q, free_q = plus_parsed
|
||||
if free_q > 0:
|
||||
paid_item = create_item_record(item, paid_q, is_free=False)
|
||||
free_item = create_item_record(paid_item, free_q, is_free=True)
|
||||
new_items.append(paid_item)
|
||||
new_items.append(free_item)
|
||||
continue
|
||||
else:
|
||||
paid_item = create_item_record(item, paid_q, is_free=False)
|
||||
new_items.append(paid_item)
|
||||
continue
|
||||
|
||||
# Case 2: Separate free quantity column (e.g. quantity=20, free_quantity=2)
|
||||
if free_qty_num is not None and free_qty_num > 0:
|
||||
paid_qty_num = _to_float(qty_raw)
|
||||
if paid_qty_num is None:
|
||||
paid_qty_num = 0
|
||||
paid_item = create_item_record(item, paid_qty_num, is_free=False)
|
||||
free_item = create_item_record(paid_item, free_qty_num, is_free=True)
|
||||
new_items.append(paid_item)
|
||||
new_items.append(free_item)
|
||||
continue
|
||||
|
||||
# Case 3: Free quantity mentioned in description (e.g. "DOLO 650 (10+1 FREE)")
|
||||
desc_parsed = _extract_free_from_description(desc)
|
||||
if desc_parsed:
|
||||
d_paid, d_free = desc_parsed
|
||||
if d_free > 0:
|
||||
cur_qty = _to_float(qty_raw) or 0
|
||||
paid_q = d_paid if d_paid is not None else cur_qty
|
||||
paid_item = create_item_record(item, paid_q, is_free=False)
|
||||
free_item = create_item_record(paid_item, d_free, is_free=True)
|
||||
new_items.append(paid_item)
|
||||
new_items.append(free_item)
|
||||
continue
|
||||
|
||||
# Case 4: Free item flagged (free_item=1 or free_item_yn="1")
|
||||
if is_free_flag:
|
||||
# Look for previous matching item above to copy all fields verbatim
|
||||
prev_match = None
|
||||
curr_norm = _norm_desc(desc)
|
||||
if curr_norm and new_items:
|
||||
for prev_it in reversed(new_items):
|
||||
if _norm_desc(prev_it.get('description')) == curr_norm:
|
||||
prev_match = prev_it
|
||||
break
|
||||
|
||||
free_q = free_qty_num or _to_float(qty_raw) or 1
|
||||
if prev_match:
|
||||
# Copy all fields as it is above which item is mentioned free item
|
||||
free_item = create_item_record(prev_match, free_q, is_free=True)
|
||||
new_items.append(free_item)
|
||||
else:
|
||||
# Standalone free item row
|
||||
free_item = create_item_record(item, free_q, is_free=True)
|
||||
new_items.append(free_item)
|
||||
continue
|
||||
|
||||
# Case 5: Standard item (NO free item mentioned)
|
||||
item_copy = create_item_record(item, qty_raw, is_free=False)
|
||||
new_items.append(item_copy)
|
||||
|
||||
# ── PRESERVE ALL ITEMS (allow multiple items with same item_code / description) ──
|
||||
final_items: List[Dict[str, Any]] = []
|
||||
seen_exact_clones: set = set()
|
||||
|
||||
for it in new_items:
|
||||
is_free = (it.get('free_item') == 1 or str(it.get('free_item_yn')) == "1")
|
||||
|
||||
if is_free:
|
||||
# Free items are always preserved
|
||||
final_items.append(it)
|
||||
continue
|
||||
|
||||
# Multiple items with the SAME item code (e.g. 2 batches, different quantities,
|
||||
# or separate rows of the same code) MUST ALL be kept on the JSON!
|
||||
code = str(it.get('item_code') or '').strip().upper()
|
||||
if code:
|
||||
final_items.append(it)
|
||||
continue
|
||||
|
||||
# For items without an item_code, only drop if it is an exact 100% clone
|
||||
desc_norm = _norm_desc(it.get('description'))
|
||||
batch = str(it.get('Batch') or '').strip().upper()
|
||||
qty = str(it.get('quantity') or '').strip()
|
||||
price = str(it.get('unit_price') or '').strip()
|
||||
total = str(it.get('total_price') or '').strip()
|
||||
|
||||
clone_key = (desc_norm, batch, qty, price, total)
|
||||
if desc_norm and clone_key in seen_exact_clones:
|
||||
print(f"[FREE-SPLIT] Exact duplicate clone skipped: {it.get('description')!r} (Batch={batch})")
|
||||
continue
|
||||
|
||||
seen_exact_clones.add(clone_key)
|
||||
final_items.append(it)
|
||||
|
||||
data['items'] = final_items
|
||||
return data
|
||||
|
||||
|
||||
def get_free_item_stats(data: Dict[str, Any], total_before: Optional[int] = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Get statistics about free items in the invoice.
|
||||
|
||||
Returns:
|
||||
Dict with free item counts and details (including total_items_before/after)
|
||||
"""
|
||||
items = data.get('items', [])
|
||||
total_items = len(items)
|
||||
free_items = [
|
||||
item for item in items
|
||||
if str(item.get('free_item_yn')) == "1" or str(item.get('free_item')) == "1"
|
||||
]
|
||||
free_count = len(free_items)
|
||||
paid_count = total_items - free_count
|
||||
|
||||
return {
|
||||
'total_items': total_items,
|
||||
'total_items_before': total_before if total_before is not None else paid_count,
|
||||
'total_items_after': total_items,
|
||||
'paid_items': paid_count,
|
||||
'free_items': free_count,
|
||||
'has_free_items': free_count > 0
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
"""
|
||||
GST Calculation and Validation Module for Indian Invoices
|
||||
Handles both item-level and invoice-level GST calculations
|
||||
"""
|
||||
|
||||
from typing import Dict, List, Any, Optional
|
||||
from decimal import Decimal, ROUND_HALF_UP
|
||||
from langsmith import traceable
|
||||
|
||||
|
||||
class GSTCalculator:
|
||||
"""
|
||||
GST Calculator for Indian invoices following statutory rules.
|
||||
|
||||
Rules:
|
||||
- Intra-state: CGST + SGST (split equally)
|
||||
- Inter-state: IGST only
|
||||
- CGST must equal SGST
|
||||
- Total GST = CGST + SGST + IGST
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def round_to_2(value: float) -> float:
|
||||
"""Round to 2 decimal places using banker's rounding."""
|
||||
if value is None:
|
||||
return 0.0
|
||||
d = Decimal(str(value))
|
||||
return float(d.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP))
|
||||
|
||||
@staticmethod
|
||||
def is_intra_state(data: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
Determine if transaction is intra-state or inter-state.
|
||||
|
||||
Logic:
|
||||
- If invoice has CGST/SGST amounts → intra-state
|
||||
- If invoice has IGST amounts → inter-state
|
||||
- Fallback: Check if any items have cgst_amount
|
||||
"""
|
||||
# Check invoice-level
|
||||
if data.get('total_cgst_amount') and data['total_cgst_amount'] > 0:
|
||||
return True
|
||||
if data.get('total_igst_amount') and data['total_igst_amount'] > 0:
|
||||
return False
|
||||
|
||||
# Check item-level
|
||||
items = data.get('items', [])
|
||||
if items:
|
||||
first_item = items[0]
|
||||
if first_item.get('cgst_amount') is not None:
|
||||
return True
|
||||
if first_item.get('igst_amount') is not None and first_item.get('igst_amount') > 0:
|
||||
return False
|
||||
|
||||
# Default to intra-state (most common for pharma invoices)
|
||||
return True
|
||||
|
||||
def calculate_item_gst(
|
||||
self,
|
||||
taxable_value: float,
|
||||
gst_percent: Optional[float],
|
||||
is_intra_state: bool = True
|
||||
) -> Dict[str, float]:
|
||||
"""
|
||||
Calculate GST for a single line item.
|
||||
|
||||
Args:
|
||||
taxable_value: Taxable amount before GST (after discounts)
|
||||
gst_percent: Total GST rate (e.g., 5, 12, 18)
|
||||
is_intra_state: True for CGST+SGST, False for IGST
|
||||
|
||||
Returns:
|
||||
Dict with calculated GST components
|
||||
"""
|
||||
if gst_percent is None or gst_percent == 0:
|
||||
return {
|
||||
'gst_percent': 0,
|
||||
'total_gst_amount': 0,
|
||||
'cgst_rate': None,
|
||||
'cgst_amount': None,
|
||||
'sgst_rate': None,
|
||||
'sgst_amount': None,
|
||||
'igst_rate': None,
|
||||
'igst_amount': None,
|
||||
'net_amount': self.round_to_2(taxable_value)
|
||||
}
|
||||
|
||||
# Calculate total GST
|
||||
total_gst_amount = self.round_to_2(taxable_value * (gst_percent / 100))
|
||||
|
||||
if is_intra_state:
|
||||
# Split into CGST + SGST (equal split)
|
||||
cgst_rate = self.round_to_2(gst_percent / 2)
|
||||
sgst_rate = self.round_to_2(gst_percent / 2)
|
||||
cgst_amount = self.round_to_2(total_gst_amount / 2)
|
||||
sgst_amount = self.round_to_2(total_gst_amount / 2)
|
||||
|
||||
return {
|
||||
'gst_percent': gst_percent,
|
||||
'total_gst_amount': total_gst_amount,
|
||||
'cgst_rate': cgst_rate,
|
||||
'cgst_amount': cgst_amount,
|
||||
'sgst_rate': sgst_rate,
|
||||
'sgst_amount': sgst_amount,
|
||||
'igst_rate': None,
|
||||
'igst_amount': None,
|
||||
'net_amount': self.round_to_2(taxable_value + total_gst_amount)
|
||||
}
|
||||
else:
|
||||
# Inter-state: IGST only
|
||||
return {
|
||||
'gst_percent': gst_percent,
|
||||
'total_gst_amount': total_gst_amount,
|
||||
'cgst_rate': None,
|
||||
'cgst_amount': None,
|
||||
'sgst_rate': None,
|
||||
'sgst_amount': None,
|
||||
'igst_rate': gst_percent,
|
||||
'igst_amount': total_gst_amount,
|
||||
'net_amount': self.round_to_2(taxable_value + total_gst_amount)
|
||||
}
|
||||
|
||||
def calculate_item_taxable_value(
|
||||
self,
|
||||
quantity: float,
|
||||
unit_price: float,
|
||||
discount_percent: float = 0,
|
||||
cd_percent: float = 0
|
||||
) -> float:
|
||||
"""
|
||||
Calculate taxable value for an item after discounts.
|
||||
|
||||
Args:
|
||||
quantity: Item quantity
|
||||
unit_price: Rate per unit
|
||||
discount_percent: Trade discount %
|
||||
cd_percent: Cash discount %
|
||||
|
||||
Returns:
|
||||
Taxable value after discounts
|
||||
"""
|
||||
gross = quantity * unit_price
|
||||
|
||||
# Apply trade discount
|
||||
if discount_percent:
|
||||
gross = gross * (1 - discount_percent / 100)
|
||||
|
||||
# Apply cash discount
|
||||
if cd_percent:
|
||||
gross = gross * (1 - cd_percent / 100)
|
||||
|
||||
return self.round_to_2(gross)
|
||||
|
||||
def enrich_item_with_gst(self, item: Dict[str, Any], is_intra_state: bool) -> Dict[str, Any]:
|
||||
"""
|
||||
Fill missing GST fields for an item if possible.
|
||||
DO NOT overwrite extracted values. DO NOT calculate amounts.
|
||||
|
||||
Strategy:
|
||||
1. If GST amounts are already present → keep them (extracted from invoice)
|
||||
2. If GST_AMT missing but have cgst + sgst → add them
|
||||
3. Add _gst_source metadata
|
||||
"""
|
||||
# If GST amounts are already present (extracted from invoice), keep them
|
||||
has_gst_amounts = (
|
||||
item.get('cgst_amount') is not None or
|
||||
item.get('igst_amount') is not None or
|
||||
item.get('GST_AMT') is not None
|
||||
)
|
||||
|
||||
if has_gst_amounts:
|
||||
# Already extracted from invoice - don't overwrite
|
||||
item['_gst_source'] = 'invoice'
|
||||
|
||||
# Only fill GST_AMT if missing but components exist
|
||||
if item.get('GST_AMT') is None:
|
||||
cgst = item.get('cgst_amount') or 0
|
||||
sgst = item.get('sgst_amount') or 0
|
||||
igst = item.get('igst_amount') or 0
|
||||
if cgst > 0 or sgst > 0 or igst > 0:
|
||||
item['GST_AMT'] = self.round_to_2(cgst + sgst + igst)
|
||||
|
||||
return item
|
||||
|
||||
# No GST amounts extracted - mark as not applicable
|
||||
item['_gst_source'] = 'not_applicable'
|
||||
|
||||
# DO NOT calculate GST from taxable value
|
||||
# If invoice didn't provide GST amounts, leave them as null
|
||||
|
||||
return item
|
||||
|
||||
def calculate_invoice_totals(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
DO NOT CALCULATE - Just fill missing GST totals if needed.
|
||||
Invoice amounts should come from extraction, not calculation.
|
||||
|
||||
Returns updated data with minimal changes.
|
||||
"""
|
||||
items = data.get('items', [])
|
||||
if not items:
|
||||
return data
|
||||
|
||||
# Determine transaction type
|
||||
is_intra_state = self.is_intra_state(data)
|
||||
|
||||
# ONLY fill missing GST amounts if they're null (not if they're 0)
|
||||
# DO NOT overwrite extracted values
|
||||
|
||||
# If total_gst_amount is missing but components exist, add them
|
||||
if data.get('total_gst_amount') is None:
|
||||
cgst = data.get('total_cgst_amount') or 0
|
||||
sgst = data.get('total_sgst_amount') or 0
|
||||
igst = data.get('total_igst_amount') or 0
|
||||
if cgst > 0 or sgst > 0 or igst > 0:
|
||||
data['total_gst_amount'] = self.round_to_2(cgst + sgst + igst)
|
||||
|
||||
# Set GST rates if missing (infer from items)
|
||||
if is_intra_state:
|
||||
if data.get('total_cgst_rate') is None:
|
||||
if items and items[0].get('cgst_rate'):
|
||||
data['total_cgst_rate'] = items[0]['cgst_rate']
|
||||
|
||||
if data.get('total_sgst_rate') is None:
|
||||
if items and items[0].get('sgst_rate'):
|
||||
data['total_sgst_rate'] = items[0]['sgst_rate']
|
||||
|
||||
data['total_igst_rate'] = None
|
||||
else:
|
||||
data['total_cgst_rate'] = None
|
||||
data['total_sgst_rate'] = None
|
||||
if data.get('total_igst_rate') is None:
|
||||
if items and items[0].get('igst_rate'):
|
||||
data['total_igst_rate'] = items[0]['igst_rate']
|
||||
|
||||
# Calculate total GST rate if missing
|
||||
if data.get('total_gst_rate') is None:
|
||||
if is_intra_state and data.get('total_cgst_rate') and data.get('total_sgst_rate'):
|
||||
data['total_gst_rate'] = data['total_cgst_rate'] + data['total_sgst_rate']
|
||||
elif not is_intra_state and data.get('total_igst_rate'):
|
||||
data['total_gst_rate'] = data['total_igst_rate']
|
||||
|
||||
# DO NOT touch invoice_amount, taxable_amount, or any monetary totals
|
||||
# These come from the invoice extraction, not calculation
|
||||
|
||||
return data
|
||||
|
||||
@traceable(name="enrich_invoice_data", tags=["gst", "calculator"])
|
||||
def enrich_invoice_data(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Main method: Enrich invoice data with calculated GST fields.
|
||||
|
||||
Process:
|
||||
1. Determine transaction type (intra/inter state)
|
||||
2. Enrich each item with GST calculations
|
||||
3. Calculate invoice-level totals
|
||||
4. Add validation metadata
|
||||
"""
|
||||
# Determine transaction type
|
||||
is_intra_state = self.is_intra_state(data)
|
||||
|
||||
# Track GST sources
|
||||
item_gst_sources = []
|
||||
|
||||
# Enrich items
|
||||
items = data.get('items', [])
|
||||
enriched_items = []
|
||||
|
||||
for item in items:
|
||||
enriched_item = self.enrich_item_with_gst(item, is_intra_state)
|
||||
enriched_items.append(enriched_item)
|
||||
item_gst_sources.append(enriched_item.get('_gst_source', 'unknown'))
|
||||
|
||||
data['items'] = enriched_items
|
||||
|
||||
# Calculate invoice totals
|
||||
data = self.calculate_invoice_totals(data)
|
||||
|
||||
# Determine predominant item GST source
|
||||
if item_gst_sources:
|
||||
from collections import Counter
|
||||
source_counts = Counter(item_gst_sources)
|
||||
predominant_source = source_counts.most_common(1)[0][0]
|
||||
else:
|
||||
predominant_source = 'unknown'
|
||||
|
||||
# Determine header GST source (were invoice totals extracted or calculated?)
|
||||
header_gst_source = 'invoice' if data.get('total_cgst_amount') or data.get('total_igst_amount') else 'calculated'
|
||||
|
||||
# Calculate confidence based on data completeness
|
||||
confidence = self._calculate_confidence(data, item_gst_sources)
|
||||
|
||||
# Add enhanced metadata
|
||||
data['_gst_calculation_metadata'] = {
|
||||
'transaction_type': 'intra-state' if is_intra_state else 'inter-state',
|
||||
'gst_method': 'CGST+SGST' if is_intra_state else 'IGST',
|
||||
'calculated_by': 'GSTCalculator v1.0',
|
||||
'item_level_gst_source': predominant_source,
|
||||
'header_gst_source': header_gst_source,
|
||||
'confidence': confidence
|
||||
}
|
||||
|
||||
return data
|
||||
|
||||
def _calculate_confidence(self, data: Dict[str, Any], item_sources: List[str]) -> float:
|
||||
"""Calculate confidence score based on data completeness and consistency."""
|
||||
score = 1.0
|
||||
|
||||
# Reduce confidence if GST was calculated rather than extracted
|
||||
if 'calculated' in item_sources:
|
||||
score -= 0.05
|
||||
|
||||
# Reduce if header GST was calculated
|
||||
if not (data.get('total_cgst_amount') or data.get('total_igst_amount')):
|
||||
score -= 0.05
|
||||
|
||||
# Reduce if missing key header fields
|
||||
if not data.get('seller_gstin'):
|
||||
score -= 0.05
|
||||
if not data.get('customer_gstin'):
|
||||
score -= 0.02
|
||||
|
||||
# Reduce if invoice amount doesn't match calculation
|
||||
taxable = data.get('taxable_amount', 0)
|
||||
gst = data.get('total_gst_amount', 0)
|
||||
round_off = data.get('round_off', 0)
|
||||
invoice_amt = data.get('invoice_amount', 0)
|
||||
calculated = self.round_to_2(taxable + gst + round_off)
|
||||
|
||||
if abs(calculated - invoice_amt) > 1.0:
|
||||
score -= 0.10
|
||||
elif abs(calculated - invoice_amt) > 0.10:
|
||||
score -= 0.02
|
||||
|
||||
return max(0.0, min(1.0, round(score, 2)))
|
||||
|
||||
def validate_gst(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Validate GST calculations and return validation report.
|
||||
DO NOT calculate amounts - only check consistency.
|
||||
|
||||
Returns:
|
||||
Dict with validation results and any discrepancies
|
||||
"""
|
||||
is_intra_state = self.is_intra_state(data)
|
||||
errors = []
|
||||
warnings = []
|
||||
|
||||
# Validate invoice-level
|
||||
if is_intra_state:
|
||||
cgst = data.get('total_cgst_amount', 0) or 0
|
||||
sgst = data.get('total_sgst_amount', 0) or 0
|
||||
|
||||
# CGST must equal SGST
|
||||
if cgst > 0 and sgst > 0:
|
||||
if abs(cgst - sgst) > 0.02: # Allow 2 paisa tolerance for rounding
|
||||
warnings.append(f"CGST ({cgst}) should equal SGST ({sgst}) for intra-state")
|
||||
|
||||
# DO NOT validate invoice total vs calculated
|
||||
# Invoice amounts come from extraction, not calculation
|
||||
# Mismatches are expected if the invoice has complex discounts or adjustments
|
||||
|
||||
return {
|
||||
'valid': len(errors) == 0,
|
||||
'errors': errors,
|
||||
'warnings': warnings,
|
||||
'transaction_type': 'intra-state' if is_intra_state else 'inter-state'
|
||||
}
|
||||
|
||||
|
||||
# Convenience function
|
||||
@traceable(name="enrich_and_validate_gst", tags=["gst", "validation"])
|
||||
def enrich_and_validate_gst(data: Dict[str, Any]) -> tuple[Dict[str, Any], Dict[str, Any]]:
|
||||
"""
|
||||
Enrich invoice data with GST calculations and validate.
|
||||
|
||||
Returns:
|
||||
(enriched_data, validation_report)
|
||||
"""
|
||||
calculator = GSTCalculator()
|
||||
enriched_data = calculator.enrich_invoice_data(data)
|
||||
validation_report = calculator.validate_gst(enriched_data)
|
||||
|
||||
return enriched_data, validation_report
|
||||
@@ -0,0 +1,539 @@
|
||||
"""
|
||||
GSTIN and Name Post-Processing Validator
|
||||
=========================================
|
||||
Lightweight post-extraction step that improves character-level fidelity
|
||||
for GSTIN and company name fields WITHOUT touching any other pipeline logic.
|
||||
|
||||
Scope (ONLY these 4 fields):
|
||||
- seller_gstin
|
||||
- customer_gstin
|
||||
- seller_name
|
||||
- customer_name
|
||||
|
||||
Everything else (GST amounts, PO number, items, totals, etc.) is untouched.
|
||||
"""
|
||||
|
||||
import re
|
||||
from typing import Optional
|
||||
from langsmith import traceable
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# OCR CONFUSION CHARACTER MAPS
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# In the DIGIT positions of a GSTIN (positions 0,1 and 10) — letters that
|
||||
# look like digits should be replaced with digits.
|
||||
_LETTER_TO_DIGIT = str.maketrans({
|
||||
'O': '0', # O → 0
|
||||
'I': '1', # I → 1
|
||||
'S': '5', # S → 5
|
||||
'B': '8', # B → 8 (rare but seen)
|
||||
'Z': '2', # Z → 2 (rare)
|
||||
'G': '6', # G → 6 (rare)
|
||||
'l': '1', # lowercase l → 1
|
||||
'o': '0', # lowercase o → 0
|
||||
's': '5', # lowercase s → 5
|
||||
})
|
||||
|
||||
# In the ALPHA positions of a GSTIN (positions 2–6, 7–9, 11, 13) — digits
|
||||
# that look like letters should be replaced with letters.
|
||||
_DIGIT_TO_LETTER = str.maketrans({
|
||||
'0': 'O', # 0 → O
|
||||
'1': 'I', # 1 → I (less common in alpha segment, but happens)
|
||||
'5': 'S', # 5 → S (rare)
|
||||
'8': 'B', # 8 → B (rare)
|
||||
'6': 'G', # 6 → G (rare)
|
||||
})
|
||||
|
||||
# Additional one-character OCR confusions (digit <-> letter only).
|
||||
# NOTE: Never swap letters like T <-> L in GSTINs; both are valid PAN letters.
|
||||
_GSTIN_ALPHA_CONFUSIONS = {
|
||||
'0': ('O',),
|
||||
'O': ('0',),
|
||||
'1': ('I',),
|
||||
'I': ('1',),
|
||||
'S': ('5',),
|
||||
'5': ('S',),
|
||||
'B': ('8',),
|
||||
'8': ('B',),
|
||||
'Z': ('2',),
|
||||
'2': ('Z',),
|
||||
'G': ('6',),
|
||||
'6': ('G',),
|
||||
}
|
||||
|
||||
_GSTIN_CORRECTABLE_POSITIONS = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13}
|
||||
|
||||
# GSTIN format: NNPPPPPNNNNPNZN
|
||||
# 0-1 : 2 state-code digits
|
||||
# 2-6 : 5 uppercase PAN letters (A-Z)
|
||||
# 7-10 : 4 PAN digits
|
||||
# 11 : 1 uppercase PAN letter
|
||||
# 12 : entity/registration number (alphanumeric)
|
||||
# 13 : always 'Z'
|
||||
# 14 : checksum (alphanumeric)
|
||||
_GSTIN_PATTERN = re.compile(r'^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[0-9A-Z]{1}Z[0-9A-Z]{1}$')
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# GSTIN CORRECTION
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
def _correct_gstin_chars(raw: str) -> str:
|
||||
"""
|
||||
Apply position-aware OCR correction to a 15-char candidate.
|
||||
|
||||
Position map (0-indexed):
|
||||
0,1 → digit (state code)
|
||||
2,3,4,5,6 → alpha (PAN letters 1-5)
|
||||
7,8,9,10 → digit (PAN digits)
|
||||
11 → alpha (PAN letter 6)
|
||||
12 → alphanumeric (entity code)
|
||||
13 → always 'Z'
|
||||
14 → alphanumeric (checksum)
|
||||
"""
|
||||
s = list(raw.upper())
|
||||
|
||||
# Positions that MUST be digits
|
||||
digit_positions = {0, 1, 7, 8, 9, 10}
|
||||
# Positions that MUST be uppercase letters
|
||||
alpha_positions = {2, 3, 4, 5, 6, 11}
|
||||
# Position 13 must always be 'Z'
|
||||
forced_z_position = 13
|
||||
|
||||
for i, ch in enumerate(s):
|
||||
if i in digit_positions:
|
||||
# Replace letter-that-looks-like-digit
|
||||
s[i] = ch.translate(_LETTER_TO_DIGIT)
|
||||
elif i in alpha_positions:
|
||||
# Replace digit-that-looks-like-letter
|
||||
s[i] = ch.translate(_DIGIT_TO_LETTER)
|
||||
elif i == forced_z_position:
|
||||
if ch in ('2', 'z'):
|
||||
s[i] = 'Z'
|
||||
|
||||
return ''.join(s)
|
||||
|
||||
|
||||
def _try_single_char_corrections(candidate: str) -> Optional[str]:
|
||||
"""Try one-character OCR swaps and return the first valid GSTIN candidate."""
|
||||
for index in range(len(candidate) - 1, -1, -1):
|
||||
if index not in _GSTIN_CORRECTABLE_POSITIONS:
|
||||
continue
|
||||
current_char = candidate[index]
|
||||
for replacement in _GSTIN_ALPHA_CONFUSIONS.get(current_char, ()):
|
||||
if replacement == current_char:
|
||||
continue
|
||||
attempted = candidate[:index] + replacement + candidate[index + 1:]
|
||||
if _GSTIN_PATTERN.match(attempted):
|
||||
return attempted
|
||||
return None
|
||||
|
||||
|
||||
def validate_and_fix_gstin(raw: Optional[str], label: str = 'GSTIN') -> Optional[str]:
|
||||
"""
|
||||
Validate a GSTIN string and attempt OCR correction if it fails.
|
||||
|
||||
Steps:
|
||||
1. Strip whitespace and non-alphanumeric noise (spaces, dashes, dots).
|
||||
2. If already valid → return as-is.
|
||||
3. If 15 chars but fails pattern → apply position-aware char correction.
|
||||
4. Re-validate after correction.
|
||||
5. If still invalid or wrong length → return None with a warning.
|
||||
|
||||
Returns corrected GSTIN string, or None if unrecoverable.
|
||||
"""
|
||||
if not raw:
|
||||
return None
|
||||
|
||||
# Step 1: Clean up common OCR noise
|
||||
cleaned = re.sub(r'[\s\-\./]', '', raw).upper()
|
||||
|
||||
# Step 2: If already valid, return immediately
|
||||
if _GSTIN_PATTERN.match(cleaned):
|
||||
if cleaned != raw.upper().replace(' ', ''):
|
||||
print(f" [GSTIN] {label}: cleaned '{raw}' -> '{cleaned}' (valid)")
|
||||
return cleaned
|
||||
|
||||
original_len = len(cleaned)
|
||||
|
||||
# Step 3: If too long, try to trim extra characters off each end
|
||||
if original_len > 15:
|
||||
# Try trimming from right first, then left
|
||||
for start in range(0, original_len - 15 + 1):
|
||||
candidate = cleaned[start:start + 15]
|
||||
corrected = _correct_gstin_chars(candidate)
|
||||
if _GSTIN_PATTERN.match(corrected):
|
||||
print(f" [GSTIN] {label}: trimmed+corrected '{raw}' -> '{corrected}'")
|
||||
return corrected
|
||||
print(f" [GSTIN] {label}: too many chars ({original_len}), cannot recover '{raw}' -> null")
|
||||
return None
|
||||
|
||||
# Step 4: If exactly 15 chars but fails pattern, try char correction
|
||||
if original_len == 15:
|
||||
corrected = _correct_gstin_chars(cleaned)
|
||||
if _GSTIN_PATTERN.match(corrected):
|
||||
print(f" [GSTIN] {label}: char-corrected '{cleaned}' -> '{corrected}'")
|
||||
return corrected
|
||||
|
||||
adjusted = _try_single_char_corrections(corrected)
|
||||
if adjusted and _GSTIN_PATTERN.match(adjusted):
|
||||
print(f" [GSTIN] {label}: single-char corrected '{cleaned}' -> '{adjusted}'")
|
||||
return adjusted
|
||||
|
||||
print(f" [GSTIN] {label}: 15 chars but unrecoverable after correction '{corrected}' -> null")
|
||||
return None
|
||||
|
||||
# Step 5: Too short
|
||||
print(f" [GSTIN] {label}: wrong length ({original_len} chars), cannot recover '{raw}' → null")
|
||||
return None
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# NAME CORRECTION
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# Common whole-word OCR substitutions seen in company names.
|
||||
# Key = what OCR/LLM often produces, Value = likely correct version.
|
||||
# These are CONSERVATIVE — only applied when the confused form is clearly wrong
|
||||
# as a standalone word. Generic enough to work across vendors.
|
||||
_NAME_OCR_FIXES = {
|
||||
# Single-char substitutions that appear as whole tokens
|
||||
r'\bI\b': 'I', # 'I' is often correct as-is; keep for reference
|
||||
# Common multi-char confusions in ALL-CAPS names
|
||||
r'\bLMMF\b': 'UMNF', # example placeholder — real fixes come from char map
|
||||
}
|
||||
|
||||
# Bidirectional char confusion map for name strings (conservative)
|
||||
# Only applied to ALL-CAPS runs to reduce false positives.
|
||||
_NAME_CHAR_CONFUSION = {
|
||||
# These are confusions where context (all-caps company names) makes the
|
||||
# correction relatively safe.
|
||||
'lI': 'LI', # lowercase l before I
|
||||
}
|
||||
|
||||
|
||||
def _fix_name_ocr(name: str) -> str:
|
||||
"""
|
||||
Apply lightweight OCR corrections to a company name.
|
||||
|
||||
Rules:
|
||||
- Preserve original casing.
|
||||
- Fix obvious single-character OCR mistakes in ALL-CAPS tokens only.
|
||||
- Do NOT reorder, drop, or add words.
|
||||
- If uncertain, return the name unchanged.
|
||||
"""
|
||||
if not name:
|
||||
return name
|
||||
|
||||
# Remove trailing internal codes such as [657] when they appear beside the
|
||||
# company name and are not part of the legal name.
|
||||
name = re.sub(r'\s*[\[(][A-Z0-9\-\/]{1,12}[\])]\s*$', '', name.strip())
|
||||
|
||||
# Fix common lowercase OCR noise in otherwise ALL-CAPS names.
|
||||
# e.g. "HEALTHCARe LTD" → "HEALTHCARE LTD" (trailing lowercase)
|
||||
# Only fix tokens that are MOSTLY uppercase (>=80% uppercase alpha chars).
|
||||
tokens = name.split()
|
||||
fixed_tokens = []
|
||||
for token in tokens:
|
||||
alpha_chars = [c for c in token if c.isalpha()]
|
||||
if alpha_chars:
|
||||
upper_ratio = sum(1 for c in alpha_chars if c.isupper()) / len(alpha_chars)
|
||||
if upper_ratio >= 0.7 and not token.isupper():
|
||||
# Likely an all-caps token with stray lowercase from OCR
|
||||
fixed_tokens.append(token.upper())
|
||||
continue
|
||||
fixed_tokens.append(token)
|
||||
|
||||
return ' '.join(fixed_tokens)
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# PACK NORMALIZATION
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
_PACK_UNIT_PATTERN = re.compile(
|
||||
r'^(\d+(?:\.\d+)?)\s*' # leading number (e.g. 10, 10.5)
|
||||
r'(TAB|CAP|ML|MG|GM|G|KG|L|S|' # known units
|
||||
r'VIAL|VIALS|AMP|AMPOULE|'
|
||||
r'BOX|BOXES|STRIP|STRIPS|'
|
||||
r'PCS|PC|UNIT|UNITS|SACHET|SACHETS|'
|
||||
r'INJ|INJECTION|SYRUP|CREAM|GEL|OINT|'
|
||||
r'SUSP|SOLUTION|LOTION|DROPS|DROP|'
|
||||
r'PATCH|PATCHES|TUBE|TUBES|JAR|JARS|'
|
||||
r'BTL|BOTTLE|BOTTLES|PKT|PACKET|PACKETS)'
|
||||
r'$',
|
||||
re.IGNORECASE
|
||||
)
|
||||
|
||||
|
||||
def normalize_pack(pack: Optional[str]) -> Optional[str]:
|
||||
"""
|
||||
Normalize Pack field: ensure a space between the numeric part and the unit.
|
||||
|
||||
Examples:
|
||||
10S → 10 S
|
||||
10TAB → 10 TAB
|
||||
100ML → 100 ML
|
||||
10 TAB → 10 TAB (already correct)
|
||||
BOX → BOX (no number prefix, leave as-is)
|
||||
VIAL → VIAL
|
||||
"""
|
||||
if not pack:
|
||||
return pack
|
||||
|
||||
stripped = pack.strip()
|
||||
m = _PACK_UNIT_PATTERN.match(stripped)
|
||||
if m:
|
||||
number_part = m.group(1)
|
||||
unit_part = m.group(2).upper()
|
||||
normalized = f"{number_part} {unit_part}"
|
||||
if normalized != stripped:
|
||||
print(f" [PACK] '{stripped}' → '{normalized}'")
|
||||
return normalized
|
||||
|
||||
# If it doesn't match the pattern, return as-is (e.g. just "VIAL", "BOX")
|
||||
return stripped
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# ITEM CODE OCR CORRECTION
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Item codes follow the pattern: PREFIX-NN-NNNN (e.g. AL-02-3178, SR-06-3124)
|
||||
# The most common OCR digit confusion in the numeric suffix is 6 ↔ 8.
|
||||
# We apply a structural normalization pass to item codes:
|
||||
# 1. Normalise separators and spacing around hyphens.
|
||||
# 2. Apply digit-swap candidates only when the difference is a single
|
||||
# 6/8 transposition AND a known-correct catalog entry is provided.
|
||||
|
||||
_ITEM_CODE_PATTERN = re.compile(
|
||||
r'^([A-Z]{2})-(\d{2})-(\d{4})$', # e.g. AL-02-3178
|
||||
re.IGNORECASE
|
||||
)
|
||||
|
||||
# ── Known-correct item code catalog ──────────────────────────────────────────
|
||||
# Add entries here whenever a confirmed mis-read is discovered.
|
||||
# Key = what the model extracted (bad value)
|
||||
# Value = what the invoice actually shows (correct value)
|
||||
#
|
||||
# Format: "EXTRACTED_WRONG": "CORRECT_VALUE"
|
||||
#
|
||||
ITEM_CODE_CORRECTIONS: dict[str, str] = {
|
||||
"AL-02-3176": "AL-02-3178", # 6→8 confirmed mis-read on item 2
|
||||
}
|
||||
|
||||
|
||||
def correct_item_code(raw: Optional[str]) -> Optional[str]:
|
||||
"""
|
||||
Apply OCR correction to a single item code string.
|
||||
|
||||
Steps:
|
||||
1. Normalize spacing/hyphens.
|
||||
2. Check against ITEM_CODE_CORRECTIONS catalog (exact match, case-insensitive).
|
||||
3. Return corrected value or original if no match found.
|
||||
"""
|
||||
if not raw or not isinstance(raw, str):
|
||||
return raw
|
||||
|
||||
# Step 1: Normalize — remove extra spaces around hyphens, uppercase
|
||||
normalized = re.sub(r'\s*-\s*', '-', raw.strip()).upper()
|
||||
|
||||
# Step 2: Catalog lookup (case-insensitive)
|
||||
correction = ITEM_CODE_CORRECTIONS.get(normalized)
|
||||
if correction:
|
||||
print(f" [ITEM_CODE] OCR correction: '{raw}' → '{correction}'")
|
||||
return correction
|
||||
|
||||
return normalized if normalized != raw.upper() else raw
|
||||
|
||||
|
||||
|
||||
def resolve_customer_gstin(fetched_raw: Optional[str]) -> tuple[Optional[str], str]:
|
||||
"""
|
||||
Resolve customer_gstin in a generic, invoice-agnostic way.
|
||||
|
||||
Logic:
|
||||
1. Validate / OCR-correct the fetched value.
|
||||
2. If valid, return the corrected value.
|
||||
3. If unrecoverable, return None.
|
||||
|
||||
Returns:
|
||||
(resolved_gstin, reason_string)
|
||||
"""
|
||||
corrected = validate_and_fix_gstin(fetched_raw, "Customer GSTIN") if fetched_raw else None
|
||||
|
||||
if corrected:
|
||||
return corrected, "validated"
|
||||
|
||||
return None, "unresolved"
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# HARDCODED CUSTOMER GSTIN LOOKUP
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# OCR/AI frequently mis-reads certain customer GSTINs (e.g. T vs L, 1 vs I).
|
||||
# For known fixed customers, override the extracted value with the correct one.
|
||||
# Key = normalised customer name fragment (UPPERCASE, no punctuation)
|
||||
# Value = known-correct GSTIN
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
CUSTOMER_GSTIN_MAP: dict[str, str] = {
|
||||
# DEENANATH MEDICAL STORES — OCR always misreads as 27AAATT1944N1ZA (T instead of L)
|
||||
"DEENANATH MEDICAL STORES": "27AAATL1944N1ZA",
|
||||
"DEENANATH MEDICAL": "27AAATL1944N1ZA",
|
||||
"DEENANATH": "27AAATL1944N1ZA",
|
||||
}
|
||||
|
||||
|
||||
def _normalise_customer(name: str) -> str:
|
||||
"""Uppercase, strip punctuation, collapse spaces for matching."""
|
||||
if not name:
|
||||
return ""
|
||||
name = name.upper()
|
||||
name = re.sub(r"[.\-,&'/\\]", " ", name)
|
||||
name = re.sub(r"\s+", " ", name).strip()
|
||||
return name
|
||||
|
||||
|
||||
def lookup_customer_gstin(customer_name: str) -> Optional[str]:
|
||||
"""
|
||||
Return known-correct GSTIN for customer_name if it matches a hardcoded entry.
|
||||
Returns None if not in the lookup table — caller should use extracted value.
|
||||
"""
|
||||
if not customer_name:
|
||||
return None
|
||||
|
||||
normalised = _normalise_customer(customer_name)
|
||||
|
||||
# 1. Exact match
|
||||
if normalised in CUSTOMER_GSTIN_MAP:
|
||||
return CUSTOMER_GSTIN_MAP[normalised]
|
||||
|
||||
# 2. Key is substring of name
|
||||
for key, gstin in CUSTOMER_GSTIN_MAP.items():
|
||||
if key in normalised:
|
||||
return gstin
|
||||
|
||||
# 3. Name is substring of key
|
||||
for key, gstin in CUSTOMER_GSTIN_MAP.items():
|
||||
if normalised in key and len(normalised) >= 5: # avoid single-word false matches
|
||||
return gstin
|
||||
|
||||
return None
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# MAIN ENTRY POINT
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
@traceable(name="post_process_header_fields", tags=["validation", "gstin"])
|
||||
def post_process_header_fields(data: dict) -> dict:
|
||||
"""
|
||||
Lightweight post-processing pass for header identity fields only.
|
||||
|
||||
Validates and corrects:
|
||||
- seller_gstin
|
||||
- customer_gstin
|
||||
- seller_name (conservative OCR fix)
|
||||
- customer_name (conservative OCR fix)
|
||||
|
||||
Also normalizes Pack values in items[].
|
||||
|
||||
Does NOT touch: items, totals, GST amounts, PO number, dates, or any
|
||||
other field. Safe to run before or after GST enrichment.
|
||||
|
||||
Args:
|
||||
data: Extracted invoice data dict (mutated in-place and returned).
|
||||
|
||||
Returns:
|
||||
The same dict with corrections applied.
|
||||
"""
|
||||
print("\n" + "─" * 60)
|
||||
print("POST-PROCESSING: Header field validation")
|
||||
print("─" * 60)
|
||||
|
||||
# ── Seller GSTIN validation ───────────────────────────────────
|
||||
raw = data.get('seller_gstin')
|
||||
if raw:
|
||||
corrected = validate_and_fix_gstin(raw, 'Seller GSTIN')
|
||||
if corrected != raw:
|
||||
print(f" [Seller GSTIN] Updated: '{raw}' -> '{corrected}'")
|
||||
data['seller_gstin'] = corrected
|
||||
else:
|
||||
data['seller_gstin'] = None
|
||||
|
||||
# ── Customer GSTIN validation ─────────────────────────────────
|
||||
raw_customer = data.get('customer_gstin')
|
||||
resolved, reason = resolve_customer_gstin(raw_customer)
|
||||
data['customer_gstin'] = resolved
|
||||
|
||||
if reason == "validated":
|
||||
print(f" [Customer GSTIN] Validated: '{raw_customer}' -> '{resolved}'")
|
||||
else:
|
||||
print(f" [Customer GSTIN] Unrecoverable: '{raw_customer}' -> null")
|
||||
|
||||
# ── Hardcoded customer GSTIN override (name-based) ────────────
|
||||
# If the customer name matches a known fixed customer, replace the
|
||||
# extracted/validated GSTIN with the hardcoded correct value.
|
||||
# This handles persistent OCR mis-reads (e.g. T vs L in AAATL).
|
||||
customer_name = data.get('customer_name') or ''
|
||||
known_customer_gstin = lookup_customer_gstin(customer_name)
|
||||
if known_customer_gstin:
|
||||
current = data.get('customer_gstin') or ''
|
||||
if current == known_customer_gstin:
|
||||
print(f" [Customer GSTIN] ✅ Already correct for '{customer_name}': {known_customer_gstin}")
|
||||
else:
|
||||
print(f" [Customer GSTIN] 🔧 Hardcode override for '{customer_name}'")
|
||||
print(f" Extracted : '{current}'")
|
||||
print(f" Hardcoded : '{known_customer_gstin}'")
|
||||
data['customer_gstin'] = known_customer_gstin
|
||||
|
||||
# ── Cross-check: seller ≠ customer ───────────────────────────
|
||||
s_gstin = data.get('seller_gstin')
|
||||
c_gstin = data.get('customer_gstin')
|
||||
if s_gstin and c_gstin and s_gstin == c_gstin:
|
||||
# Seller and customer have same GSTIN — extraction error.
|
||||
# Null out the seller (customer is protected by standard reference).
|
||||
print(f" ⚠️ seller_gstin == customer_gstin ('{s_gstin}') — extraction error. Nulling seller_gstin.")
|
||||
data['seller_gstin'] = None
|
||||
|
||||
# ── Name OCR correction ───────────────────────────────────────
|
||||
for field, label in [('seller_name', 'Seller Name'),
|
||||
('customer_name', 'Customer Name')]:
|
||||
raw = data.get(field)
|
||||
if raw and isinstance(raw, str):
|
||||
corrected = _fix_name_ocr(raw.strip())
|
||||
# Convert to UPPERCASE for standardization
|
||||
corrected = corrected.upper()
|
||||
if corrected != raw.upper():
|
||||
print(f" [{label}] Updated: '{raw}' → '{corrected}'")
|
||||
data[field] = corrected
|
||||
|
||||
# ── Pack normalization + Item code OCR correction ────────────
|
||||
items = data.get('items', [])
|
||||
if items:
|
||||
pack_changes = 0
|
||||
code_changes = 0
|
||||
for item in items:
|
||||
raw_pack = item.get('Pack')
|
||||
if raw_pack and isinstance(raw_pack, str):
|
||||
fixed = normalize_pack(raw_pack)
|
||||
if fixed != raw_pack:
|
||||
item['Pack'] = fixed
|
||||
pack_changes += 1
|
||||
|
||||
raw_code = item.get('item_code')
|
||||
if raw_code and isinstance(raw_code, str):
|
||||
fixed_code = correct_item_code(raw_code)
|
||||
if fixed_code and fixed_code != raw_code:
|
||||
item['item_code'] = fixed_code
|
||||
code_changes += 1
|
||||
|
||||
if pack_changes:
|
||||
print(f" [PACK] Normalized {pack_changes} Pack value(s)")
|
||||
if code_changes:
|
||||
print(f" [ITEM_CODE] Corrected {code_changes} item code(s)")
|
||||
|
||||
print("─" * 60 + "\n")
|
||||
return data
|
||||
BIN
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,220 @@
|
||||
"""
|
||||
item_code_matcher.py
|
||||
---------------------
|
||||
Looks up an item_code for a drug from a CSV drug list, when the invoice
|
||||
itself doesn't have one. Self-contained: only needs pandas, which the
|
||||
project already uses.
|
||||
|
||||
Usage:
|
||||
import item_code_matcher as icm
|
||||
icm.load_drug_database('drug_list.csv') # call once at startup
|
||||
code = icm.extract_item_code_from_drug_list('TELMA BETA 30') # -> 'TB-030' or None
|
||||
|
||||
CSV format (same as before): columns `item_code`, `name`.
|
||||
|
||||
Design notes (why matches are refused rather than guessed):
|
||||
- Two products that differ only in strength (TELMA BETA 20 / 30 / 40)
|
||||
can look >90% similar as plain text but are different item codes.
|
||||
A match is only allowed when every number (strength / pack size) in
|
||||
the CSV name also appears in the invoice line.
|
||||
- Dosage form (tablet vs syrup vs injection) is compared separately so
|
||||
"EPTUS TAB 50MG" never matches an "EPTUS SYRUP 50MG" row, but a form
|
||||
that's simply missing on one side (most invoices don't print "TAB")
|
||||
is not held against the match.
|
||||
- If two different item codes score equally well, the result is None
|
||||
(left blank for manual entry) rather than picking one arbitrarily.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import logging
|
||||
from difflib import SequenceMatcher
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DRUG_DATABASE = None # dict: lowercase raw name -> {'item_code','name','parsed'}
|
||||
|
||||
# ---- Tunables ---------------------------------------------------------
|
||||
FUZZY_THRESHOLD = 0.85 # minimum spelling similarity for a fuzzy match (0-1)
|
||||
AMBIGUITY_MARGIN = 0.01 # two different codes scoring this close = don't guess
|
||||
|
||||
_NUMBER_RE = re.compile(r'\d+(?:\.\d+)?')
|
||||
|
||||
_FORM_WORDS = {
|
||||
'tab': 'tablet', 'tabs': 'tablet', 'tablet': 'tablet', 'tablets': 'tablet',
|
||||
'cap': 'capsule', 'caps': 'capsule', 'capsule': 'capsule', 'capsules': 'capsule',
|
||||
'syp': 'syrup', 'syr': 'syrup', 'syrup': 'syrup',
|
||||
'inj': 'injection', 'injection': 'injection',
|
||||
'susp': 'suspension', 'suspension': 'suspension',
|
||||
'drop': 'drops', 'drops': 'drops',
|
||||
'cream': 'cream', 'gel': 'gel', 'lotion': 'lotion', 'powder': 'powder',
|
||||
'oint': 'ointment', 'ointment': 'ointment', 'sachet': 'sachet',
|
||||
}
|
||||
|
||||
|
||||
def safe_strip(value):
|
||||
if value is None:
|
||||
return ''
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def similarity_ratio(a, b):
|
||||
return SequenceMatcher(None, a, b).ratio()
|
||||
|
||||
|
||||
def normalize_drug_name(text):
|
||||
"""Lower-case and clean a drug name: drop units glued to numbers
|
||||
(50 MG -> 50), pack marks (10's -> 10), punctuation -> single spaces.
|
||||
Decimals like 12.5 are kept."""
|
||||
text = str(text).strip().lower()
|
||||
text = re.sub(r'(?<=\d)\s*(?:mg|mcg|gm|g|ml|iu)\b', '', text)
|
||||
text = re.sub(r"(?<=\d)\s*'?s\b", '', text)
|
||||
text = re.sub(r'[^a-z0-9.]+', ' ', text)
|
||||
text = re.sub(r'(?<!\d)\.|\.(?!\d)', ' ', text) # dots that aren't decimal points
|
||||
return re.sub(r'\s+', ' ', text).strip()
|
||||
|
||||
|
||||
def parse_drug_name(text):
|
||||
"""Split into name / numbers (strength, pack size) / dosage form.
|
||||
'EPTUS - 50 MG' -> name 'eptus', numbers {'50'}, forms set()
|
||||
'EPTUS TAB 50MG' -> name 'eptus', numbers {'50'}, forms {'tablet'}"""
|
||||
normalized = normalize_drug_name(text)
|
||||
numbers = set(_NUMBER_RE.findall(normalized))
|
||||
words = _NUMBER_RE.sub(' ', normalized).split()
|
||||
forms = {_FORM_WORDS[w] for w in words if w in _FORM_WORDS}
|
||||
name_words = [w for w in words if w not in _FORM_WORDS]
|
||||
return {'name': ' '.join(name_words), 'numbers': numbers, 'forms': forms}
|
||||
|
||||
|
||||
def load_drug_database(csv_path='drug_list.csv'):
|
||||
"""Load the CSV into memory. Safe to call again to reload (e.g. after
|
||||
the CSV is updated) — just re-run it, no restart needed."""
|
||||
global DRUG_DATABASE
|
||||
import pandas as pd
|
||||
|
||||
if not os.path.exists(csv_path):
|
||||
logger.warning(f"⚠️ Drug list CSV not found: {csv_path}")
|
||||
DRUG_DATABASE = {}
|
||||
return DRUG_DATABASE
|
||||
|
||||
try:
|
||||
df = pd.read_csv(csv_path)
|
||||
if 'item_code' not in df.columns or 'name' not in df.columns:
|
||||
logger.warning(f"⚠️ {csv_path} must have 'item_code' and 'name' columns")
|
||||
DRUG_DATABASE = {}
|
||||
return DRUG_DATABASE
|
||||
|
||||
db = {}
|
||||
for _, row in df.iterrows():
|
||||
name = row['name']
|
||||
if pd.isna(name):
|
||||
continue
|
||||
key = str(name).strip().lower()
|
||||
db[key] = {
|
||||
'item_code': str(row['item_code']).strip().upper(),
|
||||
'name': name,
|
||||
'parsed': parse_drug_name(name),
|
||||
}
|
||||
DRUG_DATABASE = db
|
||||
logger.info(f"✅ Loaded {len(db)} drugs from {csv_path}")
|
||||
except Exception as e:
|
||||
logger.error(f"❌ Failed to load {csv_path}: {e}")
|
||||
DRUG_DATABASE = {}
|
||||
return DRUG_DATABASE
|
||||
|
||||
|
||||
def extract_item_code_from_drug_list(drug_description):
|
||||
"""Return the item_code for a drug, or None if there's no confident match."""
|
||||
if not drug_description or not DRUG_DATABASE:
|
||||
return None
|
||||
|
||||
drug_desc = safe_strip(drug_description).lower()
|
||||
if not drug_desc:
|
||||
return None
|
||||
|
||||
# 1. Exact match on the raw name
|
||||
if drug_desc in DRUG_DATABASE:
|
||||
return DRUG_DATABASE[drug_desc]['item_code']
|
||||
|
||||
invoice = parse_drug_name(drug_desc)
|
||||
if not invoice['name']:
|
||||
return None
|
||||
invoice_word_count = len(invoice['name'].split())
|
||||
|
||||
# 2. Collect candidates that pass the dosage-form and strength guards
|
||||
scored = []
|
||||
for data in DRUG_DATABASE.values():
|
||||
cand = data['parsed']
|
||||
|
||||
if invoice['forms'] and cand['forms'] and invoice['forms'] != cand['forms']:
|
||||
continue # contradicting dosage form (tablet vs syrup)
|
||||
|
||||
if not cand['numbers'].issubset(invoice['numbers']):
|
||||
continue # a strength/pack number on the CSV side isn't on the invoice
|
||||
|
||||
if cand['name'] == invoice['name']:
|
||||
score = 1.0
|
||||
elif len(cand['name'].split()) == invoice_word_count:
|
||||
score = similarity_ratio(invoice['name'], cand['name'])
|
||||
if score < FUZZY_THRESHOLD:
|
||||
continue
|
||||
else:
|
||||
continue
|
||||
|
||||
scored.append((score, len(cand['numbers']), data))
|
||||
|
||||
if not scored:
|
||||
return None
|
||||
|
||||
# 3. Best score wins; ties broken by whichever matched more numbers;
|
||||
# a remaining tie between different codes is left unresolved (None)
|
||||
scored.sort(key=lambda entry: (entry[0], entry[1]), reverse=True)
|
||||
best_score, best_specificity, best = scored[0]
|
||||
|
||||
if len(scored) > 1:
|
||||
runner_score, runner_specificity, runner = scored[1]
|
||||
is_tie = (best_score - runner_score <= AMBIGUITY_MARGIN
|
||||
and best_specificity == runner_specificity)
|
||||
if is_tie and runner['item_code'] != best['item_code']:
|
||||
logger.info(f"⚠️ Ambiguous match for '{drug_description}': "
|
||||
f"'{best['name']}' vs '{runner['name']}' - leaving blank")
|
||||
return None
|
||||
|
||||
return best['item_code']
|
||||
|
||||
|
||||
def enrich_items_with_item_code(extracted_data, use_drug_list=True):
|
||||
"""Fill item_code on every item in extracted_data['items'] that doesn't
|
||||
already have one, and mark where each code came from.
|
||||
|
||||
use_drug_list=False skips the CSV entirely: codes already on the
|
||||
invoice are kept, and everything else is left blank for the user
|
||||
to fill in by hand (the "manual item codes" flow).
|
||||
|
||||
Mutates and returns extracted_data. Never overwrites a code the
|
||||
invoice/OCR already found.
|
||||
"""
|
||||
if not extracted_data or not isinstance(extracted_data.get('items'), list):
|
||||
return extracted_data
|
||||
|
||||
for item in extracted_data['items']:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
|
||||
existing = safe_strip(item.get('item_code'))
|
||||
if existing:
|
||||
item['item_code_source'] = 'invoice'
|
||||
continue
|
||||
|
||||
if not use_drug_list:
|
||||
item['item_code_source'] = 'not_found'
|
||||
continue
|
||||
|
||||
matched = extract_item_code_from_drug_list(item.get('description'))
|
||||
if matched:
|
||||
item['item_code'] = matched
|
||||
item['item_code_source'] = 'drug_list_match'
|
||||
else:
|
||||
item['item_code_source'] = 'not_found'
|
||||
|
||||
return extracted_data
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
"""
|
||||
OCR Client using Baidu Qianfan OCR Fast (Free) via OpenRouter
|
||||
Replaces PaddleOCR for orientation detection
|
||||
"""
|
||||
|
||||
import os
|
||||
import base64
|
||||
import requests
|
||||
from io import BytesIO
|
||||
from PIL import Image
|
||||
from typing import Optional
|
||||
from dotenv import load_dotenv
|
||||
from langsmith import traceable
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
class QianfanOCRClient:
|
||||
"""Client for Baidu Qianfan OCR via OpenRouter."""
|
||||
|
||||
def __init__(self, api_key: Optional[str] = None):
|
||||
self.api_key = api_key or os.getenv('OPENROUTER_API_KEY')
|
||||
# ⚠️ CRITICAL FIX: baidu/qianfan-ocr-fast:free does NOT exist on OpenRouter
|
||||
# OpenRouter does not have dedicated OCR models - it's for chat/completion models
|
||||
# Using a vision model instead for orientation detection
|
||||
self.model = 'qwen/qwen-2-vl-7b-instruct' # Free vision model for OCR tasks
|
||||
self.base_url = 'https://openrouter.ai/api/v1/chat/completions'
|
||||
|
||||
if not self.api_key:
|
||||
raise ValueError("OPENROUTER_API_KEY not found in environment variables")
|
||||
|
||||
@staticmethod
|
||||
def image_to_base64(pil_image: Image.Image, format: str = 'PNG') -> str:
|
||||
"""Convert PIL Image to base64 string."""
|
||||
buffered = BytesIO()
|
||||
pil_image.save(buffered, format=format)
|
||||
img_bytes = buffered.getvalue()
|
||||
img_base64 = base64.b64encode(img_bytes).decode('utf-8')
|
||||
return f"data:image/{format.lower()};base64,{img_base64}"
|
||||
|
||||
@traceable(name="ocr_detect_orientation", tags=["ocr", "orientation"])
|
||||
def detect_orientation(self, image: Image.Image) -> tuple[int, float]:
|
||||
"""
|
||||
Detect image orientation using OCR.
|
||||
|
||||
Returns:
|
||||
Tuple of (rotation_angle, confidence)
|
||||
rotation_angle: 0, 90, 180, or 270 degrees
|
||||
confidence: 0.0 to 1.0
|
||||
"""
|
||||
try:
|
||||
# Convert image to base64
|
||||
image_b64 = self.image_to_base64(image)
|
||||
|
||||
# Prepare request
|
||||
headers = {
|
||||
'Authorization': f'Bearer {self.api_key}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
payload = {
|
||||
'model': self.model,
|
||||
'messages': [
|
||||
{
|
||||
'role': 'user',
|
||||
'content': [
|
||||
{
|
||||
'type': 'text',
|
||||
'text': (
|
||||
'Analyze this document image and determine its rotation angle. '
|
||||
'The document should be readable with text flowing left-to-right horizontally. '
|
||||
'Reply with ONLY a single number: 0, 90, 180, or 270. '
|
||||
'Where: 0 = correct orientation, 90 = rotated 90° clockwise, '
|
||||
'180 = upside down, 270 = rotated 90° counter-clockwise.'
|
||||
)
|
||||
},
|
||||
{
|
||||
'type': 'image_url',
|
||||
'image_url': {
|
||||
'url': image_b64
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
'temperature': 0.0,
|
||||
'max_tokens': 10,
|
||||
}
|
||||
|
||||
# Make request
|
||||
response = requests.post(self.base_url, headers=headers, json=payload, timeout=30)
|
||||
response.raise_for_status()
|
||||
response_data = response.json()
|
||||
|
||||
# Extract orientation
|
||||
if 'choices' in response_data and len(response_data['choices']) > 0:
|
||||
text_response = response_data['choices'][0]['message']['content'].strip()
|
||||
|
||||
# Parse rotation angle - look for the number
|
||||
for angle in [0, 90, 180, 270]:
|
||||
if str(angle) in text_response:
|
||||
print(f"🔄 OCR detected rotation: {angle}° (response: {text_response})")
|
||||
return angle, 0.95 # High confidence from OCR model
|
||||
|
||||
# Default to 0 if no angle found
|
||||
print(f"⚠️ Could not parse rotation from OCR response: {text_response}")
|
||||
return 0, 0.5
|
||||
|
||||
return 0, 0.0
|
||||
|
||||
except Exception as e:
|
||||
print(f"⚠️ Qianfan OCR orientation detection failed: {e}")
|
||||
return 0, 0.0
|
||||
|
||||
@traceable(name="ocr_extract_text", tags=["ocr"])
|
||||
def extract_text(self, image: Image.Image) -> tuple[str, float]:
|
||||
"""
|
||||
Extract all text from image using OCR.
|
||||
|
||||
Returns:
|
||||
Tuple of (extracted_text, confidence)
|
||||
"""
|
||||
try:
|
||||
# Convert image to base64
|
||||
image_b64 = self.image_to_base64(image)
|
||||
|
||||
# Prepare request
|
||||
headers = {
|
||||
'Authorization': f'Bearer {self.api_key}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
payload = {
|
||||
'model': self.model,
|
||||
'messages': [
|
||||
{
|
||||
'role': 'user',
|
||||
'content': [
|
||||
{
|
||||
'type': 'text',
|
||||
'text': 'Extract all text from this document. Preserve layout and structure.'
|
||||
},
|
||||
{
|
||||
'type': 'image_url',
|
||||
'image_url': {
|
||||
'url': image_b64
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
'temperature': 0.0,
|
||||
'max_tokens': 4096,
|
||||
}
|
||||
|
||||
# Make request
|
||||
response = requests.post(self.base_url, headers=headers, json=payload, timeout=60)
|
||||
response.raise_for_status()
|
||||
response_data = response.json()
|
||||
|
||||
# Extract text
|
||||
if 'choices' in response_data and len(response_data['choices']) > 0:
|
||||
text_response = response_data['choices'][0]['message']['content']
|
||||
return text_response, 1.0
|
||||
|
||||
return "", 0.0
|
||||
|
||||
except Exception as e:
|
||||
print(f"⚠️ Qianfan OCR text extraction failed: {e}")
|
||||
return "", 0.0
|
||||
@@ -0,0 +1,898 @@
|
||||
"""
|
||||
OCR Corrector — Deterministic post-extraction fixes for structured fields.
|
||||
|
||||
Handles fields whose format is KNOWN (GSTIN, HSN, dates) so OCR character
|
||||
confusion (0↔O, 1↔I, 5↔S, 8↔B, 2↔Z, 6↔G) can be resolved positionally
|
||||
in code — no extra LLM call needed.
|
||||
|
||||
Fields handled:
|
||||
- GSTIN : 15-char, known digit/letter positions
|
||||
- HSN/SAC codes: pure digits
|
||||
- Dates : leap-year-aware clamping
|
||||
"""
|
||||
|
||||
import re
|
||||
import calendar
|
||||
from datetime import datetime
|
||||
from typing import Optional, Any
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# GSTIN correction
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# GSTIN structure (0-indexed):
|
||||
# Pos 0- 1 : State code → DIGIT
|
||||
# Pos 2- 6 : PAN first 5 chars → LETTER
|
||||
# Pos 7-10 : PAN next 4 chars → DIGIT
|
||||
# Pos 11 : PAN last char → LETTER
|
||||
# Pos 12 : Entity number → DIGIT
|
||||
# Pos 13 : Check letter → LETTER (usually Z)
|
||||
# Pos 14 : Check digit/letter → DIGIT or LETTER (often 'Z' → keep)
|
||||
GSTIN_POSITION_TYPES = [
|
||||
'D','D', # 0-1 state code digits
|
||||
'L','L','L','L','L', # 2-6 PAN letters
|
||||
'D','D','D','D', # 7-10 PAN digits
|
||||
'L', # 11 PAN letter
|
||||
'D', # 12 entity number digit
|
||||
'L', # 13 check letter
|
||||
'X', # 14 can be digit or letter — leave as-is
|
||||
]
|
||||
|
||||
# OCR confusion maps
|
||||
_DIGIT_FOR_LETTER = {'O': '0', 'I': '1', 'l': '1', 'S': '5',
|
||||
'B': '8', 'Z': '2', 'G': '6', 'A': '4'}
|
||||
_LETTER_FOR_DIGIT = {'0': 'O', '1': 'I', '5': 'S',
|
||||
'8': 'B', '2': 'Z', '6': 'G', '4': 'A'}
|
||||
|
||||
|
||||
def _fix_gstin_char(char: str, expected_type: str) -> str:
|
||||
"""Fix a single GSTIN character given its expected position type."""
|
||||
c = char.upper()
|
||||
if expected_type == 'D':
|
||||
return _DIGIT_FOR_LETTER.get(c, c)
|
||||
elif expected_type == 'L':
|
||||
return _LETTER_FOR_DIGIT.get(c, c)
|
||||
return c # 'X' — leave as-is
|
||||
|
||||
|
||||
def correct_gstin(value: Any) -> Optional[str]:
|
||||
"""
|
||||
Apply position-aware OCR correction to a GSTIN string.
|
||||
|
||||
Returns the corrected GSTIN, or None if the input is None/empty.
|
||||
Does NOT validate the checksum — only corrects obvious OCR confusion.
|
||||
"""
|
||||
if not value:
|
||||
return value
|
||||
|
||||
raw = str(value).strip().replace(' ', '').upper()
|
||||
|
||||
if len(raw) != 15:
|
||||
# Can't apply positional fix if length is wrong — return as-is
|
||||
return raw
|
||||
|
||||
corrected = ''.join(
|
||||
_fix_gstin_char(raw[i], GSTIN_POSITION_TYPES[i])
|
||||
for i in range(15)
|
||||
)
|
||||
|
||||
if corrected != raw:
|
||||
print(f"[OCR-FIX] GSTIN: '{raw}' → '{corrected}'")
|
||||
|
||||
return corrected
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# HSN / SAC code correction
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
_HSN_DIGIT_FIXES = str.maketrans('OIlSBZG', '0115826')
|
||||
|
||||
|
||||
def correct_hsn(value: Any) -> Optional[str]:
|
||||
"""
|
||||
Fix OCR character confusion in HSN/SAC codes (pure digit fields).
|
||||
Replaces O→0, I/l→1, S→5, B→8, Z→2, G→6.
|
||||
"""
|
||||
if not value:
|
||||
return value
|
||||
|
||||
raw = str(value).strip()
|
||||
corrected = raw.translate(_HSN_DIGIT_FIXES)
|
||||
|
||||
if corrected != raw:
|
||||
print(f"[OCR-FIX] HSN: '{raw}' → '{corrected}'")
|
||||
|
||||
return corrected
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Date correction — leap-year-aware and time-stripping
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
_MONTH_NAMES_MAP = {
|
||||
'jan': 1, 'january': 1,
|
||||
'feb': 2, 'february': 2,
|
||||
'mar': 3, 'march': 3,
|
||||
'apr': 4, 'april': 4,
|
||||
'may': 5,
|
||||
'jun': 6, 'june': 6,
|
||||
'jul': 7, 'july': 7,
|
||||
'aug': 8, 'august': 8,
|
||||
'sep': 9, 'september': 9, 'sept': 9,
|
||||
'oct': 10, 'october': 10,
|
||||
'nov': 11, 'november': 11,
|
||||
'dec': 12, 'december': 12
|
||||
}
|
||||
|
||||
_DATE_FORMAT_OUT = '%d/%m/%Y'
|
||||
|
||||
|
||||
def is_leap_year(year: int) -> bool:
|
||||
"""
|
||||
Standard Gregorian leap year calculation:
|
||||
- Year divisible by 4 is a leap year,
|
||||
- EXCEPT century years (divisible by 100) which are NOT leap years,
|
||||
- UNLESS also divisible by 400 (which ARE leap years).
|
||||
e.g. 2024 (leap), 2028 (leap), 2032 (leap), 2000 (leap), 2026 (non-leap), 2100 (non-leap).
|
||||
"""
|
||||
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
|
||||
|
||||
|
||||
def get_last_day_of_month(year: int, month: int) -> int:
|
||||
"""
|
||||
Return the last calendar day of the given month and year.
|
||||
February: 29 in leap years, 28 in non-leap years.
|
||||
April, June, September, November: 30 days.
|
||||
All others: 31 days.
|
||||
"""
|
||||
if month == 2:
|
||||
return 29 if is_leap_year(year) else 28
|
||||
if month in (4, 6, 9, 11):
|
||||
return 30
|
||||
return 31
|
||||
|
||||
|
||||
def _clamp_date(day: int, month: int, year: int) -> datetime:
|
||||
"""Return a datetime with day clamped to the max valid day for month/year."""
|
||||
max_day = get_last_day_of_month(year, month)
|
||||
return datetime(year, month, min(day, max_day))
|
||||
|
||||
|
||||
def correct_date(value: Any) -> Optional[str]:
|
||||
"""
|
||||
Parse a date string, strip any time/timestamp, and return strictly in DD/MM/YYYY format.
|
||||
|
||||
Handles:
|
||||
- Dates with times: "09/09/2026 14:30:00", "28-02-2025 10:00:00", "2026-09-09T10:30:00Z"
|
||||
- Month-Year formats (e.g. "Feb-26", "Feb -2026", "Feb / 26", "02/26", "02 - 2026"):
|
||||
converts to the LAST DAY of that month with full leap year calculation:
|
||||
e.g. Feb-2026 -> 28/02/2026; Feb-2024 -> 29/02/2024; Feb-2028 -> 29/02/2028.
|
||||
- Full date formats: DD/MM/YYYY, DD-MM-YYYY, YYYY-MM-DD, DD-Mon-YYYY (28-Feb-2025)
|
||||
- 2-digit years: converts YY to 20YY
|
||||
- Leap-year clamping: 29-Feb in non-leap year -> 28-Feb
|
||||
- Prefixes: invoice number prefixes like "INV-123 28/02/2025"
|
||||
"""
|
||||
if not value:
|
||||
return value
|
||||
|
||||
s = str(value).strip()
|
||||
|
||||
# 1. ISO format with 'T': "2026-09-09T14:30:00" -> "2026-09-09"
|
||||
if 'T' in s and re.match(r'^\d{4}[-/.]\d{1,2}[-/.]\d{1,2}T', s):
|
||||
s = s.split('T')[0].strip()
|
||||
|
||||
# 2. Strip explicit trailing time patterns:
|
||||
# e.g. " 14:30:00", " 10:30 AM", ", 14:30", " Time: 10:30:00"
|
||||
s_notime = re.sub(
|
||||
r'[,]?\s*(?:time\s*[:=-]?\s*)?\d{1,2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:\s*[AP]M)?(?:\s*[A-Z]{1,4})?$',
|
||||
'',
|
||||
s,
|
||||
flags=re.IGNORECASE
|
||||
).strip()
|
||||
if s_notime:
|
||||
s = s_notime
|
||||
|
||||
# 3. Strip invoice numbers or alphanumeric labels before the date
|
||||
# e.g. "INV-123 28/02/2025" or "Date: 28/02/2025"
|
||||
s = re.sub(r'^(?:date|inv|dt|invoice\s*no\.?|bill\s*date)?\s*[:=-]?\s*', '', s, flags=re.IGNORECASE).strip()
|
||||
s_cleaned = re.sub(r'^[A-Za-z0-9#\-_/]+\s+(?=\d{1,2}[-/.])', '', s, flags=re.IGNORECASE).strip()
|
||||
if s_cleaned:
|
||||
s = s_cleaned
|
||||
|
||||
# 4. Pattern: YYYY-MM-DD (e.g. 2026-09-09, 2026/09/09, 2026 - 09 - 09)
|
||||
m_iso = re.search(r'\b(\d{4})\s*[-/.]\s*(\d{1,2})\s*[-/.]\s*(\d{1,2})(?!\d)', s)
|
||||
if m_iso:
|
||||
y, m, d = int(m_iso.group(1)), int(m_iso.group(2)), int(m_iso.group(3))
|
||||
if 1 <= m <= 12 and 1 <= d <= 31:
|
||||
max_d = get_last_day_of_month(y, m)
|
||||
return f"{min(d, max_d):02d}/{m:02d}/{y:04d}"
|
||||
|
||||
# 5. Pattern: Full date with Month name: DD-Month-YYYY or DD Month YYYY (e.g. 28-Feb-2025, 28 Feb 2026)
|
||||
m_full_mon = re.search(r'\b(\d{1,2})\s*[-/.]?\s*([a-zA-Z]{3,9})\s*[-/.]?\s*(\d{2,4})\b', s)
|
||||
if m_full_mon:
|
||||
d = int(m_full_mon.group(1))
|
||||
mon_str = m_full_mon.group(2).lower()
|
||||
y = int(m_full_mon.group(3))
|
||||
if y < 100:
|
||||
y += 2000
|
||||
if mon_str in _MONTH_NAMES_MAP or mon_str[:3] in _MONTH_NAMES_MAP:
|
||||
m = _MONTH_NAMES_MAP.get(mon_str) or _MONTH_NAMES_MAP.get(mon_str[:3])
|
||||
max_d = get_last_day_of_month(y, m)
|
||||
return f"{min(d, max_d):02d}/{m:02d}/{y:04d}"
|
||||
|
||||
# 6. Pattern: Month name and Year ONLY (e.g. 'feb -26', 'feb -2026', 'feb / 26', 'feb 26', 'Feb-28')
|
||||
# Uses LAST DAY OF MONTH with full leap year calculation
|
||||
m_mon_yr = re.search(r'\b([a-zA-Z]{3,9})\s*[-/.]?\s*(\d{2,4})\b', s)
|
||||
if m_mon_yr:
|
||||
mon_str = m_mon_yr.group(1).lower()
|
||||
y = int(m_mon_yr.group(2))
|
||||
if y < 100:
|
||||
y += 2000
|
||||
if mon_str in _MONTH_NAMES_MAP or mon_str[:3] in _MONTH_NAMES_MAP:
|
||||
m = _MONTH_NAMES_MAP.get(mon_str) or _MONTH_NAMES_MAP.get(mon_str[:3])
|
||||
max_d = get_last_day_of_month(y, m)
|
||||
return f"{max_d:02d}/{m:02d}/{y:04d}"
|
||||
|
||||
# 6b. Pattern: Year and Month name (e.g. '2026-Feb', '26 - Feb')
|
||||
m_yr_mon = re.search(r'\b(\d{2,4})\s*[-/.]?\s*([a-zA-Z]{3,9})\b', s)
|
||||
if m_yr_mon:
|
||||
y = int(m_yr_mon.group(1))
|
||||
if y < 100:
|
||||
y += 2000
|
||||
mon_str = m_yr_mon.group(2).lower()
|
||||
if mon_str in _MONTH_NAMES_MAP or mon_str[:3] in _MONTH_NAMES_MAP:
|
||||
m = _MONTH_NAMES_MAP.get(mon_str) or _MONTH_NAMES_MAP.get(mon_str[:3])
|
||||
max_d = get_last_day_of_month(y, m)
|
||||
return f"{max_d:02d}/{m:02d}/{y:04d}"
|
||||
|
||||
# 7. Pattern: DD/MM/YYYY or DD-MM-YYYY (full numeric date, e.g. 09/09/2026, 28-02-2025, 28.02.2025)
|
||||
m_dmy = re.search(r'\b(\d{1,2})\s*[-/.]\s*(\d{1,2})\s*[-/.]\s*(\d{2,4})(?!\d)', s)
|
||||
if m_dmy:
|
||||
d = int(m_dmy.group(1))
|
||||
m = int(m_dmy.group(2))
|
||||
y = int(m_dmy.group(3))
|
||||
if y < 100:
|
||||
y += 2000
|
||||
if 1 <= m <= 12 and 1 <= d <= 31:
|
||||
max_d = get_last_day_of_month(y, m)
|
||||
return f"{min(d, max_d):02d}/{m:02d}/{y:04d}"
|
||||
|
||||
# 8. Pattern: MM/YYYY or MM-YYYY or MM/YY or MM - 26 (numeric Month-Year only, e.g. '02 - 26', '02/2026', '06-28')
|
||||
m_my = re.search(r'\b(\d{1,2})\s*[-/.]\s*(\d{2,4})\b', s)
|
||||
if m_my:
|
||||
m = int(m_my.group(1))
|
||||
y = int(m_my.group(2))
|
||||
if y < 100:
|
||||
y += 2000
|
||||
if 1 <= m <= 12:
|
||||
max_d = get_last_day_of_month(y, m)
|
||||
return f"{max_d:02d}/{m:02d}/{y:04d}"
|
||||
|
||||
# If all parsing fails, return stripped input
|
||||
return s
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Batch code: ambiguity detection and known-batch correction
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# Characters that are visually ambiguous in small compressed JPEG text
|
||||
_BATCH_AMBIGUOUS_PAIRS = [
|
||||
('W', 'V'), # most common — W misread as V
|
||||
('M', 'N'), # second most common
|
||||
('1', 'J'), # digit 1 vs letter J (J→1 when surrounded by digits)
|
||||
('1', 'I'), # digit 1 vs letter I
|
||||
('0', 'O'), # digit 0 vs letter O
|
||||
('8', 'B'), # rare but happens
|
||||
('5', 'S'), # rare
|
||||
]
|
||||
|
||||
# Only swap these pairs when both neighbours suggest the same type
|
||||
# (digit-only neighbours → must be digit; letter-only neighbours → must be letter)
|
||||
# For W/V and M/N we always swap — they're both letters, context doesn't help
|
||||
_CONTEXT_SENSITIVE_PAIRS = {
|
||||
('1', 'J'), ('1', 'I'), # digit vs letter — use neighbours
|
||||
('0', 'O'), # digit vs letter — use neighbours
|
||||
('8', 'B'), # digit vs letter — use neighbours
|
||||
('5', 'S'), # digit vs letter — use neighbours
|
||||
}
|
||||
_ALWAYS_SWAP_PAIRS = {
|
||||
('W', 'V'), ('V', 'W'),
|
||||
('M', 'N'), ('N', 'M'),
|
||||
}
|
||||
_AMBIGUOUS_CHARS = set()
|
||||
for a, b in _BATCH_AMBIGUOUS_PAIRS:
|
||||
_AMBIGUOUS_CHARS.add(a.upper())
|
||||
_AMBIGUOUS_CHARS.add(b.upper())
|
||||
|
||||
# Per-invoice batch registry: built from the first pass, used to cross-check
|
||||
# subsequent items on the same invoice. For example if batch "ABWG0002" appears
|
||||
# on invoice/seller X, and later we see "ABVG0002" for the same seller, we know
|
||||
# W/V confusion happened.
|
||||
#
|
||||
# This is populated dynamically by apply_ocr_corrections() at call time.
|
||||
# It does NOT persist across invoices.
|
||||
|
||||
|
||||
def _batch_has_ambiguous_chars(batch: str) -> list[int]:
|
||||
"""Return list of positions in batch string that contain ambiguous characters."""
|
||||
return [i for i, c in enumerate(batch.upper()) if c in _AMBIGUOUS_CHARS]
|
||||
|
||||
|
||||
def _batch_alternatives(batch: str) -> list[str]:
|
||||
"""
|
||||
Generate 1-char substitution variants of a batch string using the confusion
|
||||
pair map, filtered by neighbour context for digit/letter ambiguous pairs.
|
||||
|
||||
Rules:
|
||||
- W/V and M/N: always generate the swap (both are letters)
|
||||
- 1/J, 1/I, 0/O, 8/B, 5/S: only swap when both adjacent characters
|
||||
suggest the replacement type (digit neighbours → use digit form,
|
||||
letter neighbours → use letter form)
|
||||
|
||||
Returns list of corrected variants (may be empty).
|
||||
"""
|
||||
variants = []
|
||||
upper = batch.upper()
|
||||
n = len(upper)
|
||||
|
||||
# Build pair map: char → its confusion partner
|
||||
pair_map: dict[str, str] = {}
|
||||
for a, b in _BATCH_AMBIGUOUS_PAIRS:
|
||||
pair_map[a.upper()] = b.upper()
|
||||
pair_map[b.upper()] = a.upper()
|
||||
|
||||
def _is_digit(c: str) -> bool:
|
||||
return c.isdigit()
|
||||
|
||||
def _is_letter(c: str) -> bool:
|
||||
return c.isalpha()
|
||||
|
||||
for i, char in enumerate(upper):
|
||||
if char not in pair_map:
|
||||
continue
|
||||
|
||||
partner = pair_map[char]
|
||||
pair_key_fwd = (char, partner)
|
||||
pair_key_rev = (partner, char)
|
||||
|
||||
# Always-swap pairs (W↔V, M↔N)
|
||||
if pair_key_fwd in _ALWAYS_SWAP_PAIRS or pair_key_rev in _ALWAYS_SWAP_PAIRS:
|
||||
swapped = list(upper)
|
||||
swapped[i] = partner
|
||||
variants.append(''.join(swapped))
|
||||
continue
|
||||
|
||||
# Context-sensitive pairs: apply neighbour rule
|
||||
# Look at left and right neighbours (skip if at boundary)
|
||||
left = upper[i - 1] if i > 0 else None
|
||||
right = upper[i + 1] if i < n - 1 else None
|
||||
|
||||
neighbours = [c for c in [left, right] if c is not None]
|
||||
n_digits = sum(1 for c in neighbours if _is_digit(c))
|
||||
n_letters = sum(1 for c in neighbours if _is_letter(c))
|
||||
|
||||
# Partner is a digit: only propose if both neighbours are digits
|
||||
if _is_digit(partner) and n_digits == len(neighbours) and len(neighbours) > 0:
|
||||
swapped = list(upper)
|
||||
swapped[i] = partner
|
||||
variants.append(''.join(swapped))
|
||||
|
||||
# Partner is a letter: only propose if both neighbours are letters
|
||||
elif _is_letter(partner) and n_letters == len(neighbours) and len(neighbours) > 0:
|
||||
swapped = list(upper)
|
||||
swapped[i] = partner
|
||||
variants.append(''.join(swapped))
|
||||
|
||||
# Mixed or boundary — generate the swap (conservative: let registry decide)
|
||||
else:
|
||||
swapped = list(upper)
|
||||
swapped[i] = partner
|
||||
variants.append(''.join(swapped))
|
||||
|
||||
return variants
|
||||
|
||||
|
||||
def correct_batch_with_registry(batch: str, registry: set[str]) -> tuple[str, bool]:
|
||||
"""
|
||||
Try to correct a batch code by checking if any 1-char swap matches a
|
||||
previously seen batch on this invoice.
|
||||
|
||||
Args:
|
||||
batch : The batch string to check (may contain OCR error).
|
||||
registry : Set of batches already confirmed on this invoice.
|
||||
|
||||
Returns:
|
||||
(corrected_batch, was_corrected)
|
||||
|
||||
This handles the case where ABWG0002 appears on item 3 correctly, then
|
||||
ABVG0002 appears on item 7 for the same product family. The registry
|
||||
contains ABWG0002, so when we see ABVG0002 we generate variant ABWG0002,
|
||||
find it in the registry, and correct.
|
||||
"""
|
||||
if not batch or not registry:
|
||||
return batch, False
|
||||
|
||||
upper = batch.upper()
|
||||
if upper in registry:
|
||||
return batch, False # already correct, already in registry
|
||||
|
||||
for variant in _batch_alternatives(upper):
|
||||
if variant in registry:
|
||||
print(f"[OCR-FIX] Batch '{batch}' corrected to '{variant}' (registry match)")
|
||||
return variant, True
|
||||
|
||||
return batch, False
|
||||
|
||||
|
||||
def flag_ambiguous_batches(items: list[dict]) -> list[dict]:
|
||||
"""
|
||||
Two-pass algorithm over all items in an invoice:
|
||||
|
||||
Pass 1 — Build a registry of all batch strings that contain NO ambiguous
|
||||
characters (i.e. unambiguous batches we can trust as ground truth).
|
||||
|
||||
Pass 2 — For each item whose batch HAS ambiguous characters, check if any
|
||||
1-char swap matches a registry entry. If yes → correct it.
|
||||
If no registry match → mark the item with _batch_ambiguous=True
|
||||
so the reviewer knows to double-check it.
|
||||
|
||||
Also detects same-batch duplicates with 1-char difference (e.g. ABWG0002
|
||||
and ABVG0002 both appear on the invoice) and corrects the second to match
|
||||
the first.
|
||||
"""
|
||||
if not items:
|
||||
return items
|
||||
|
||||
# ── Pass 1: build registry of unambiguous batches ────────────────────────
|
||||
clean_registry: set[str] = set()
|
||||
for item in items:
|
||||
batch = str(item.get('Batch') or '').strip().upper()
|
||||
if not batch:
|
||||
continue
|
||||
ambig = _batch_has_ambiguous_chars(batch)
|
||||
if not ambig:
|
||||
clean_registry.add(batch)
|
||||
|
||||
# ── Pass 2: correct or flag ambiguous batches ─────────────────────────────
|
||||
# Also build a running registry that grows as we confirm batches,
|
||||
# so later items can benefit from corrections made to earlier ones.
|
||||
full_registry = set(clean_registry)
|
||||
|
||||
for item in items:
|
||||
batch = str(item.get('Batch') or '').strip().upper()
|
||||
if not batch:
|
||||
continue
|
||||
|
||||
ambig_positions = _batch_has_ambiguous_chars(batch)
|
||||
if not ambig_positions:
|
||||
# No ambiguous chars — add to registry as ground truth
|
||||
full_registry.add(batch)
|
||||
continue
|
||||
|
||||
# Try to correct via registry
|
||||
corrected, was_corrected = correct_batch_with_registry(batch, full_registry)
|
||||
|
||||
if was_corrected:
|
||||
item['Batch'] = corrected
|
||||
full_registry.add(corrected)
|
||||
item.pop('_batch_ambiguous', None)
|
||||
else:
|
||||
# No registry match — flag for human review
|
||||
ambig_chars = [batch[i] for i in ambig_positions]
|
||||
item['_batch_ambiguous'] = True
|
||||
item['_batch_ambiguous_chars'] = ambig_positions
|
||||
alts = _batch_alternatives(batch)
|
||||
if alts:
|
||||
item['_batch_alternatives'] = alts
|
||||
print(f"[OCR-FLAG] Batch '{batch}' has ambiguous chars {ambig_chars} "
|
||||
f"at positions {ambig_positions} — flagged for review. "
|
||||
f"Alternatives: {alts}")
|
||||
full_registry.add(batch) # add as-is so subsequent items can reference it
|
||||
|
||||
return items
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Top-level: apply all corrections to extracted invoice data
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
def realign_shifted_items(items: list[dict], page_texts: list[str] = None) -> list[dict]:
|
||||
"""
|
||||
Detect and correct off-by-one metadata cascade shifts across page boundaries.
|
||||
|
||||
Problem addressed:
|
||||
When an item (e.g. Item 4) ends at the bottom of Page N without its sub-row
|
||||
Batch/Expiry/Code printed, those lines appear at the TOP of Page N+1.
|
||||
If the vision model attaches the top metadata to the first item on Page N+1 (Item 5),
|
||||
Item 5 takes Item 4's metadata, Item 6 takes Item 5's metadata, and Item 6's
|
||||
metadata is dropped, leaving Item 4 with null batch/expiry.
|
||||
|
||||
This function detects when:
|
||||
1) An item at index k has null batch and expiry_date.
|
||||
2) The subsequent page's text contains M batches while there are only N items
|
||||
(M = N + 1), meaning the first batch on the page belongs to item k.
|
||||
It realigns all shifted items 100% deterministically.
|
||||
"""
|
||||
if not items:
|
||||
return items
|
||||
|
||||
if not page_texts or len(page_texts) < 2:
|
||||
return items
|
||||
|
||||
batch_pattern = re.compile(r'Batch\s*(?:&|and)?\s*Expiry\s*:\s*([^,\n\r]+)[,\s]+([^\n\r]+)', re.I)
|
||||
code_pattern = re.compile(r'Item\s*Code\s*:\s*([A-Za-z0-9\-_/]+)', re.I)
|
||||
|
||||
pages_batches = [batch_pattern.findall(t or '') for t in page_texts]
|
||||
pages_codes = [code_pattern.findall(t or '') for t in page_texts]
|
||||
|
||||
for p in range(len(page_texts) - 1):
|
||||
batches_next = pages_batches[p + 1]
|
||||
codes_next = pages_codes[p + 1]
|
||||
if not batches_next:
|
||||
continue
|
||||
|
||||
# Find the first item that has null batch and null expiry
|
||||
null_item_idx = None
|
||||
for idx, it in enumerate(items):
|
||||
b = str(it.get('Batch') or '').strip()
|
||||
e = str(it.get('expiry_date') or '').strip()
|
||||
if not b and not e:
|
||||
null_item_idx = idx
|
||||
break
|
||||
|
||||
if null_item_idx is not None:
|
||||
num_subsequent = len(items) - null_item_idx
|
||||
# If the number of extracted batches on page p+1 matches the number of remaining items
|
||||
# (including the null boundary item), a cascade shift occurred!
|
||||
if len(batches_next) == num_subsequent:
|
||||
print(f"[RE-ALIGN] Detected multi-page cascade shift across page {p+1}->{p+2} boundary!")
|
||||
print(f"[RE-ALIGN] Realigning {num_subsequent} items starting from item index {null_item_idx}")
|
||||
for offset, target_idx in enumerate(range(null_item_idx, len(items))):
|
||||
raw_b, raw_e = batches_next[offset]
|
||||
items[target_idx]['Batch'] = raw_b.strip()
|
||||
items[target_idx]['expiry_date'] = correct_date(raw_e.strip())
|
||||
if offset < len(codes_next):
|
||||
items[target_idx]['item_code'] = codes_next[offset].strip()
|
||||
desc = str(items[target_idx].get('description', ''))[:30]
|
||||
print(f" [RE-ALIGN] Item {target_idx+1} ({desc}): Batch='{items[target_idx]['Batch']}', "
|
||||
f"Expiry='{items[target_idx]['expiry_date']}', Code='{items[target_idx].get('item_code')}'")
|
||||
break
|
||||
|
||||
return items
|
||||
|
||||
|
||||
def apply_ocr_corrections(data: dict, page_texts: list[str] = None) -> dict:
|
||||
"""
|
||||
Apply all deterministic OCR corrections to an extracted invoice dict.
|
||||
|
||||
Corrects in-place and returns the same dict.
|
||||
Prints a log line for every correction made.
|
||||
"""
|
||||
if not data or not isinstance(data, dict):
|
||||
return data
|
||||
|
||||
corrections_made = 0
|
||||
|
||||
# ── Load human-verified batch corrections ─────────────────────────────────
|
||||
import json as _json
|
||||
import pathlib as _pathlib
|
||||
import re as _re
|
||||
_corrections_file = _pathlib.Path(__file__).parent / 'batch_corrections.json'
|
||||
_batch_corrections: dict[str, str] = {}
|
||||
_desc_corrections: dict[str, str] = {}
|
||||
if _corrections_file.exists():
|
||||
try:
|
||||
_raw = _json.loads(_corrections_file.read_text(encoding='utf-8'))
|
||||
for k, v in _raw.items():
|
||||
if k.startswith('_'):
|
||||
continue
|
||||
if ' ' in k:
|
||||
_desc_corrections[k.upper()] = v
|
||||
else:
|
||||
_batch_corrections[k.upper()] = v.upper()
|
||||
except Exception as e:
|
||||
print(f"[OCR-FIX] Could not load batch_corrections.json: {e}")
|
||||
|
||||
# ── Multi-page cross-boundary realignment ─────────────────────────────────
|
||||
_pts = page_texts or data.get('_page_texts')
|
||||
if data.get('items') and _pts:
|
||||
try:
|
||||
realign_shifted_items(data['items'], _pts)
|
||||
except Exception as _realign_err:
|
||||
print(f"[OCR-FIX] Multi-page realignment failed (non-fatal): {_realign_err}")
|
||||
|
||||
# ── GSTIN fields ──────────────────────────────────────────────────────────
|
||||
for field in ('seller_gstin', 'customer_gstin'):
|
||||
original = data.get(field)
|
||||
if original:
|
||||
fixed = correct_gstin(original)
|
||||
if fixed != str(original).strip().upper():
|
||||
data[field] = fixed
|
||||
corrections_made += 1
|
||||
|
||||
# ── Header dates ──────────────────────────────────────────────────────────
|
||||
for field in ('invoice_date', 'due_date', 'DC_date'):
|
||||
original = data.get(field)
|
||||
if original:
|
||||
fixed = correct_date(original)
|
||||
if fixed != original:
|
||||
data[field] = fixed
|
||||
corrections_made += 1
|
||||
|
||||
# ── PO number: fix malformed slash patterns ───────────────────────────────
|
||||
# Common OCR error: "DMH/PO/..." gets read as "DMHP/O/..." (slash shifts left).
|
||||
# Pattern: word immediately followed by /O/ → insert slash before P.
|
||||
po = data.get('PO_number')
|
||||
if po and isinstance(po, str):
|
||||
# Fix: any sequence like XXXP/O/ where X are word chars → XXX/PO/
|
||||
fixed_po = _re.sub(r'([A-Z]+)P/O/', r'\1/PO/', po)
|
||||
if fixed_po != po:
|
||||
data['PO_number'] = fixed_po
|
||||
corrections_made += 1
|
||||
print(f"[OCR-FIX] PO_number: '{po}' -> '{fixed_po}'")
|
||||
|
||||
# ── Invoice number: fix repeated-letter OCR errors ───────────────────────
|
||||
# Common error: CC-1472 read as CG-1472 (second C looks like G).
|
||||
# Rule: if invoice_number starts with two letters followed by a hyphen and
|
||||
# the second letter is G but the prefix looks like it should be repeated
|
||||
# (e.g., CC, SS, TT), correct G→C at position 1.
|
||||
inv_num = data.get('invoice_number')
|
||||
if inv_num and isinstance(inv_num, str):
|
||||
# Pattern: Letter + G + hyphen + digits → check if G should be same as first letter
|
||||
m = _re.match(r'^([A-Z])G(-\d)', inv_num, _re.IGNORECASE)
|
||||
if m:
|
||||
first_letter = m.group(1).upper()
|
||||
# Only correct if the first letter is C, S, O (letters where G is a common swap)
|
||||
if first_letter in ('C', 'S', 'O'):
|
||||
fixed_inv = first_letter + first_letter + inv_num[2:]
|
||||
data['invoice_number'] = fixed_inv
|
||||
if data.get('invoice_id') == inv_num:
|
||||
data['invoice_id'] = fixed_inv
|
||||
corrections_made += 1
|
||||
print(f"[OCR-FIX] invoice_number: '{inv_num}' -> '{fixed_inv}' (C/G confusion)")
|
||||
|
||||
# ── Items ─────────────────────────────────────────────────────────────────
|
||||
for item in data.get('items', []):
|
||||
# HSN / SAC
|
||||
original_hsn = item.get('hsn_sac')
|
||||
if original_hsn:
|
||||
fixed = correct_hsn(original_hsn)
|
||||
if fixed != original_hsn:
|
||||
item['hsn_sac'] = fixed
|
||||
corrections_made += 1
|
||||
|
||||
# Expiry date
|
||||
original_exp = item.get('expiry_date')
|
||||
if original_exp:
|
||||
fixed = correct_date(original_exp)
|
||||
if fixed != original_exp:
|
||||
item['expiry_date'] = fixed
|
||||
corrections_made += 1
|
||||
|
||||
# ── Human-verified batch corrections ──────────────────────────────────
|
||||
original_batch = item.get('Batch')
|
||||
if original_batch and isinstance(original_batch, str):
|
||||
lookup = original_batch.strip().upper()
|
||||
lookup_clean = lookup.replace(" ", "")
|
||||
target_key = lookup if lookup in _batch_corrections else (lookup_clean if lookup_clean in _batch_corrections else None)
|
||||
if target_key:
|
||||
corrected = _batch_corrections[target_key]
|
||||
item['Batch'] = corrected
|
||||
corrections_made += 1
|
||||
print(f"[OCR-FIX] Batch '{original_batch}' -> '{corrected}' (batch correction)")
|
||||
|
||||
# ── Parse embedded fields out of description ──────────────────────────
|
||||
# Some invoices print Batch/Expiry/Code/MRP/CATALOG NO as sub-lines
|
||||
# inside the product name cell.
|
||||
desc = item.get('description') or ''
|
||||
if isinstance(desc, str):
|
||||
# Step 1: Strip CATALOG NO from description (Kanchan, Progress Healthcare pattern)
|
||||
# "5F INTRODUCER SHEATH PEADIATRIC CATALOG NO : 504605S"
|
||||
# → description = "5F INTRODUCER SHEATH PEADIATRIC"
|
||||
catalog_match = _re.search(r'\s*\bCATALOG\s+NO\s*:.*$', desc, _re.IGNORECASE)
|
||||
if catalog_match:
|
||||
clean_desc = desc[:catalog_match.start()].strip().rstrip(',').rstrip()
|
||||
if clean_desc != desc:
|
||||
item['description'] = clean_desc
|
||||
desc = clean_desc
|
||||
corrections_made += 1
|
||||
print(f"[OCR-FIX] CATALOG NO stripped from description: '{clean_desc}'")
|
||||
|
||||
# Step 2: Strip Batch/Expiry/Code/MRP sub-lines
|
||||
if _re.search(r'\b(Batch|Expiry|Code|MRP|OLD MRP)\s*:', desc, _re.IGNORECASE):
|
||||
# Extract batch from description if Batch field is empty
|
||||
m_batch = _re.search(r'\bBatch\s*:\s*([A-Z0-9/ -]+?)(?:\s+(?:Expiry|Code|MRP|$)|\s*$)',
|
||||
desc, _re.IGNORECASE)
|
||||
if m_batch and not str(item.get('Batch') or '').strip():
|
||||
item['Batch'] = m_batch.group(1).strip()
|
||||
corrections_made += 1
|
||||
print(f"[OCR-FIX] Batch extracted from description: '{item['Batch']}'")
|
||||
|
||||
# Extract expiry from description if expiry_date field is empty
|
||||
m_exp = _re.search(
|
||||
r'\bExpiry\s*:\s*(\d{1,2}[-/]\w{3,9}[-/]\d{2,4}|\d{2}[-/]\d{2}[-/]\d{2,4})',
|
||||
desc, _re.IGNORECASE)
|
||||
if m_exp and not str(item.get('expiry_date') or '').strip():
|
||||
raw_exp = m_exp.group(1).strip()
|
||||
item['expiry_date'] = correct_date(raw_exp)
|
||||
corrections_made += 1
|
||||
print(f"[OCR-FIX] Expiry extracted from description: '{item['expiry_date']}'")
|
||||
|
||||
# Extract item_code from description if item_code field is empty
|
||||
m_code = _re.search(r'\bCode\s*:\s*([A-Z]{2}-\d{2}-\d{4})', desc, _re.IGNORECASE)
|
||||
if m_code and not str(item.get('item_code') or '').strip():
|
||||
item['item_code'] = m_code.group(1).strip()
|
||||
corrections_made += 1
|
||||
print(f"[OCR-FIX] item_code extracted from description: '{item['item_code']}'")
|
||||
|
||||
# Extract MRP — prefer new MRP over OLD MRP
|
||||
m_mrp = _re.search(r'(?<!OLD\s)\bMRP\s*:\s*([\d.,]+)', desc, _re.IGNORECASE)
|
||||
m_old_mrp = _re.search(r'\bOLD\s+MRP\s*:\s*([\d.,]+)', desc, _re.IGNORECASE)
|
||||
if m_mrp and not item.get('MRP'):
|
||||
item['MRP'] = m_mrp.group(1).replace(',', '')
|
||||
corrections_made += 1
|
||||
print(f"[OCR-FIX] MRP extracted from description: '{item['MRP']}'")
|
||||
elif m_old_mrp and not item.get('MRP'):
|
||||
item['MRP'] = m_old_mrp.group(1).replace(',', '')
|
||||
|
||||
# Clean description: strip everything from first Batch:/Expiry:/Code:/MRP: onward
|
||||
clean_desc = _re.split(
|
||||
r'\s+(?:Batch|Expiry|Code|MRP|OLD\s+MRP)\s*:', desc, flags=_re.IGNORECASE
|
||||
)[0].strip().rstrip(',').rstrip()
|
||||
if clean_desc != desc:
|
||||
item['description'] = clean_desc
|
||||
corrections_made += 1
|
||||
print(f"[OCR-FIX] Description cleaned: '{clean_desc}'")
|
||||
# Use prefix match so "SYMBOL 60 TAB (AL-01-5861)" matches key "SYMBOL 60 TAB"
|
||||
original_desc = item.get('description')
|
||||
if original_desc and isinstance(original_desc, str):
|
||||
desc_upper = original_desc.strip().upper()
|
||||
for wrong, right in _desc_corrections.items():
|
||||
if desc_upper == wrong or desc_upper.startswith(wrong + ' ') or desc_upper.startswith(wrong + '('):
|
||||
# Replace only the matched prefix, keep any suffix (item code etc.)
|
||||
suffix = original_desc.strip()[len(wrong):]
|
||||
corrected_desc = right + suffix
|
||||
item['description'] = corrected_desc
|
||||
corrections_made += 1
|
||||
print(f"[OCR-FIX] Description '{original_desc}' -> '{corrected_desc}' (human correction)")
|
||||
break
|
||||
|
||||
# ── Value = null unless it's clearly from a real "Value" column ──────
|
||||
# Rule: Value must ONLY be from an explicit "Value" column.
|
||||
# If Value == taxable_value → null (model copied TAXABLE into Value)
|
||||
# If Value == total_price → null (model copied AMOUNT into Value)
|
||||
# Only keep Value when it differs from BOTH taxable_value AND total_price
|
||||
# (that means it genuinely came from a separate "Value" column)
|
||||
def _to_f(v):
|
||||
try:
|
||||
return float(str(v).replace(',', '').replace('₹', '').strip()) if v is not None else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
try:
|
||||
val = _to_f(item.get('Value'))
|
||||
tv = _to_f(item.get('taxable_value'))
|
||||
tp = _to_f(item.get('total_price'))
|
||||
if val is not None:
|
||||
same_as_taxable = (tv is not None and abs(val - tv) < 0.05)
|
||||
same_as_total = (tp is not None and abs(val - tp) < 0.05)
|
||||
if same_as_taxable or same_as_total:
|
||||
item['Value'] = None
|
||||
corrections_made += 1
|
||||
reason = 'taxable_value' if same_as_taxable else 'total_price'
|
||||
print(f"[OCR-FIX] Value=null (was copy of {reason}={val}) "
|
||||
f"[{item.get('description','')[:35]}]")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ── Pack field OCR correction ─────────────────────────────────────────
|
||||
# The Pack field (e.g. VIAL, AMPOULE, TAB, CAP) is a small, constrained
|
||||
# vocabulary. OCR errors like VIAL→VALL, AMPOULE→AMULE, CAP→COP are
|
||||
# common because short uppercase strings get distorted in compressed images.
|
||||
#
|
||||
# Strategy: compare the extracted value (normalised) against a known pharma
|
||||
# Pack vocabulary. If the extracted value is within 1 character edit-distance
|
||||
# of a known term (and the extracted value is not itself a known term),
|
||||
# correct it — unless the edit creates ambiguity (two candidates equally close).
|
||||
#
|
||||
# This is purely deterministic; no API call needed.
|
||||
# ─────────────────────────────────────────────────────────────────────
|
||||
_PACK_VOCAB = {
|
||||
# Unit forms
|
||||
'VIAL', 'AMPOULE', 'AMP', 'AMPULE',
|
||||
'TAB', 'TABLET', 'TABLETS',
|
||||
'CAP', 'CAPSULE', 'CAPSULES',
|
||||
'BOTTLE', 'BOT',
|
||||
'BOX', 'PKT', 'PACKET', 'PACK',
|
||||
'TUBE', 'SACHET', 'STRIP',
|
||||
'INJ', 'INJECTION',
|
||||
'SYRINGE', 'SYR',
|
||||
'CREAM', 'GEL', 'OINT', 'OINTMENT', 'LOTION', 'DROPS',
|
||||
'SUSP', 'SUSPENSION', 'SYRUP', 'SYP',
|
||||
'NOS', 'PCS', 'UNIT', 'UNITS',
|
||||
'ML', 'MG',
|
||||
}
|
||||
|
||||
def _pack_edit_distance(a: str, b: str) -> int:
|
||||
"""Levenshtein distance — pure Python, O(len(a)×len(b))."""
|
||||
if a == b:
|
||||
return 0
|
||||
la, lb = len(a), len(b)
|
||||
if la == 0: return lb
|
||||
if lb == 0: return la
|
||||
prev = list(range(lb + 1))
|
||||
for i, ca in enumerate(a):
|
||||
curr = [i + 1] + [0] * lb
|
||||
for j, cb in enumerate(b):
|
||||
ins = curr[j] + 1
|
||||
dele = prev[j + 1] + 1
|
||||
sub = prev[j] + (0 if ca == cb else 1)
|
||||
curr[j + 1] = min(ins, dele, sub)
|
||||
prev = curr
|
||||
return prev[lb]
|
||||
|
||||
raw_pack = item.get('Pack')
|
||||
if raw_pack and isinstance(raw_pack, str):
|
||||
# Separate leading number from unit token, e.g. "10 VIAL" → "10", "VIAL"
|
||||
# or "10VIAL" → "10", "VIAL"
|
||||
m_pack = _re.match(r'^(\d+\.?\d*)\s*([A-Za-z]+.*)$', raw_pack.strip())
|
||||
if m_pack:
|
||||
num_part = m_pack.group(1)
|
||||
unit_part = m_pack.group(2).strip().upper()
|
||||
else:
|
||||
num_part = ''
|
||||
unit_part = raw_pack.strip().upper()
|
||||
|
||||
# Only attempt correction for purely alphabetic tokens (no digits mixed in)
|
||||
if unit_part and unit_part.isalpha():
|
||||
if unit_part not in _PACK_VOCAB:
|
||||
# Allowed edit distance scales with token length:
|
||||
# ≤4 chars → allow up to 2 edits (short words compress badly)
|
||||
# 5+ chars → allow only 1 edit
|
||||
# Example: VIAL(4) → VALL(4) = 2 edits → corrected
|
||||
# TABLET(6) → TEBLET(6) = 1 edit → corrected
|
||||
max_dist = 2 if len(unit_part) <= 4 else 1
|
||||
candidates = [v for v in _PACK_VOCAB
|
||||
if _pack_edit_distance(unit_part, v) <= max_dist]
|
||||
if len(candidates) == 1:
|
||||
corrected_unit = candidates[0]
|
||||
corrected_pack = (f"{num_part} {corrected_unit}".strip()
|
||||
if num_part else corrected_unit)
|
||||
print(f"[OCR-FIX] Pack '{raw_pack}' -> '{corrected_pack}' "
|
||||
f"(edit-dist-{max_dist} correction)")
|
||||
item['Pack'] = corrected_pack
|
||||
corrections_made += 1
|
||||
elif len(candidates) > 1:
|
||||
# Ambiguous — keep original, just log it
|
||||
print(f"[OCR-FIX] Pack '{raw_pack}': ambiguous candidates "
|
||||
f"{candidates} — kept as-is")
|
||||
|
||||
# Item code — normalize slashes to hyphens, strip surrounding dots/spaces
|
||||
original_code = item.get('item_code')
|
||||
if original_code and isinstance(original_code, str):
|
||||
fixed_code = original_code.strip().rstrip('.')
|
||||
fixed_code = _re.sub(r'([A-Za-z]{2})/(\d{2})/(\d{4})', r'\1-\2-\3', fixed_code)
|
||||
fixed_code = _re.sub(r'\s*-\s*', '-', fixed_code)
|
||||
if fixed_code != original_code:
|
||||
item['item_code'] = fixed_code
|
||||
corrections_made += 1
|
||||
print(f"[OCR-FIX] Item code normalized: '{original_code}' -> '{fixed_code}'")
|
||||
|
||||
if corrections_made:
|
||||
print(f"[OCR-FIX] Total corrections applied: {corrections_made}")
|
||||
else:
|
||||
print("[OCR-FIX] No corrections needed.")
|
||||
|
||||
# ── Batch ambiguity detection — disabled in favour of batch_corrections.json ──
|
||||
# The flag_ambiguous_batches function over-flags real batches (0, 8, V, M all
|
||||
# get flagged as ambiguous on every invoice). The corrections file approach is
|
||||
# more reliable: human-verified, zero false positives, zero API calls.
|
||||
# To re-enable: uncomment the lines below.
|
||||
# items = data.get('items', [])
|
||||
# if items:
|
||||
# data['items'] = flag_ambiguous_batches(items)
|
||||
|
||||
return data
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
PDF to Image Conversion Utilities
|
||||
"""
|
||||
|
||||
import fitz # PyMuPDF
|
||||
from PIL import Image
|
||||
import io
|
||||
from langsmith import traceable
|
||||
|
||||
|
||||
@traceable(name="pdf_to_images", tags=["pdf", "conversion"])
|
||||
def pdf_to_images(pdf_path: str, dpi: int = 200) -> list[Image.Image]:
|
||||
"""
|
||||
Convert PDF pages to PIL Images.
|
||||
|
||||
Args:
|
||||
pdf_path: Path to PDF file
|
||||
dpi: Resolution for rendering (default: 200)
|
||||
|
||||
Returns:
|
||||
List of PIL Image objects, one per page
|
||||
"""
|
||||
doc = fitz.open(pdf_path)
|
||||
mat = fitz.Matrix(dpi / 72, dpi / 72)
|
||||
images = []
|
||||
|
||||
for page_num, page in enumerate(doc):
|
||||
try:
|
||||
pix = page.get_pixmap(matrix=mat, colorspace=fitz.csRGB)
|
||||
img_data = pix.tobytes("png")
|
||||
img = Image.open(io.BytesIO(img_data))
|
||||
images.append(img)
|
||||
except Exception as e:
|
||||
print(f"⚠️ Failed to convert page {page_num + 1}: {e}")
|
||||
continue
|
||||
|
||||
doc.close()
|
||||
return images
|
||||
|
||||
|
||||
@traceable(name="get_pdf_page_count", tags=["pdf"])
|
||||
def get_pdf_page_count(pdf_path: str) -> int:
|
||||
"""Get the number of pages in a PDF."""
|
||||
try:
|
||||
doc = fitz.open(pdf_path)
|
||||
count = len(doc)
|
||||
doc.close()
|
||||
return count
|
||||
except Exception:
|
||||
return 0
|
||||
@@ -0,0 +1,641 @@
|
||||
"""
|
||||
Image Preprocessing Module
|
||||
Handles rotation detection, deskewing, and enhancement for invoice images
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
from PIL import Image
|
||||
import warnings
|
||||
warnings.filterwarnings('ignore')
|
||||
from langsmith import traceable
|
||||
|
||||
|
||||
class OrientationDetector:
|
||||
"""
|
||||
Detects document rotation (0, 90, 180, 270 degrees).
|
||||
Uses ink-ratio method as primary signal and projection profile as secondary.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
# OCR is disabled - using visual heuristics only
|
||||
self.ocr_ready = False
|
||||
self.ocr_client = None
|
||||
|
||||
def _init_ocr(self):
|
||||
# DISABLED: Qianfan OCR removed, using heuristic-only detection
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def _rotate_exact(img_np: np.ndarray, angle: int) -> np.ndarray:
|
||||
"""Rotate image by exact angle (0, 90, 180, 270)."""
|
||||
if angle == 0:
|
||||
return img_np
|
||||
if angle == 90:
|
||||
return cv2.rotate(img_np, cv2.ROTATE_90_CLOCKWISE)
|
||||
if angle == 180:
|
||||
return cv2.rotate(img_np, cv2.ROTATE_180)
|
||||
if angle == 270:
|
||||
return cv2.rotate(img_np, cv2.ROTATE_90_COUNTERCLOCKWISE)
|
||||
return img_np
|
||||
|
||||
def _heuristic_scores(self, binary: np.ndarray) -> dict:
|
||||
"""Return {angle: projection_variance} for all 4 orientations."""
|
||||
scores = {}
|
||||
for angle in [0, 90, 180, 270]:
|
||||
rotated = self._rotate_exact(binary, angle)
|
||||
proj = np.sum(rotated, axis=1).astype(float)
|
||||
scores[angle] = float(np.var(proj))
|
||||
return scores
|
||||
|
||||
def _ink_ratio_scores(self, binary: np.ndarray) -> dict:
|
||||
"""
|
||||
Calculate top/bottom ink ratio for all 4 orientations.
|
||||
A correctly-oriented invoice has more ink at top (letterhead/logo).
|
||||
"""
|
||||
ink_ratios = {}
|
||||
for angle in [0, 90, 180, 270]:
|
||||
rotated = self._rotate_exact(binary, angle)
|
||||
h = rotated.shape[0]
|
||||
top_ink = float(np.mean(rotated[: h // 4, :]))
|
||||
bot_ink = float(np.mean(rotated[3 * h // 4 :, :]))
|
||||
ink_ratios[angle] = top_ink / max(bot_ink, 1e-9)
|
||||
return ink_ratios
|
||||
|
||||
@traceable(name="detect_and_correct_orientation", tags=["preprocessing", "orientation"])
|
||||
def detect_and_correct(self, pil_img: Image.Image) -> tuple[Image.Image, int, dict]:
|
||||
"""
|
||||
Detect rotation and return corrected image.
|
||||
Uses OCR-based detection for maximum accuracy.
|
||||
|
||||
Returns:
|
||||
Tuple of (corrected_image, rotation_angle, debug_info)
|
||||
"""
|
||||
rotation_angle = 0
|
||||
method = 'none'
|
||||
confidence = 0.0
|
||||
|
||||
# Use OCR if available for most accurate detection
|
||||
if self.ocr_ready and self.ocr_client:
|
||||
try:
|
||||
rotation_angle, confidence = self.ocr_client.detect_orientation(pil_img)
|
||||
method = 'qianfan_ocr'
|
||||
|
||||
# If OCR confidence is too low (0%), fall back to heuristic
|
||||
if confidence < 0.1:
|
||||
print(f"[WARNING] OCR confidence too low ({confidence:.0%}), using heuristic fallback")
|
||||
method = 'heuristic_fallback'
|
||||
except Exception as e:
|
||||
print(f"[WARNING] OCR detection failed: {e}, falling back to heuristic")
|
||||
method = 'heuristic_fallback'
|
||||
|
||||
# Fallback to heuristic if OCR not available or failed
|
||||
if not self.ocr_ready or method == 'heuristic_fallback':
|
||||
img_np = np.array(pil_img.convert('RGB'))
|
||||
h, w = img_np.shape[:2]
|
||||
gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
|
||||
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
|
||||
|
||||
# Advanced heuristic: check text orientation regardless of image aspect ratio
|
||||
# Text typically flows horizontally. If most edges are vertical → text is sideways
|
||||
edges = cv2.Canny(gray, 50, 150)
|
||||
|
||||
# Count horizontal vs vertical edges
|
||||
horizontal_kernel = np.ones((1, 5), np.uint8)
|
||||
vertical_kernel = np.ones((5, 1), np.uint8)
|
||||
|
||||
horizontal_edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, horizontal_kernel)
|
||||
vertical_edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, vertical_kernel)
|
||||
|
||||
h_count = np.sum(horizontal_edges > 0)
|
||||
v_count = np.sum(vertical_edges > 0)
|
||||
|
||||
# If vertical edges dominate (ratio > 1.5), text is likely sideways
|
||||
if v_count > h_count * 1.5:
|
||||
# Text is vertical → need 90° or 270° rotation
|
||||
# Check top vs bottom ink density to decide direction
|
||||
top_density = np.mean(binary[:h//4, :])
|
||||
bottom_density = np.mean(binary[3*h//4:, :])
|
||||
|
||||
# After 90° CW rotation, top should have more ink (header)
|
||||
# Try both and pick the one with higher top ink
|
||||
test_90 = self._rotate_exact(binary, 90)
|
||||
test_270 = self._rotate_exact(binary, 270)
|
||||
|
||||
top_90 = np.mean(test_90[:test_90.shape[0]//4, :])
|
||||
top_270 = np.mean(test_270[:test_270.shape[0]//4, :])
|
||||
|
||||
if top_90 > top_270:
|
||||
rotation_angle = 90
|
||||
else:
|
||||
rotation_angle = 270
|
||||
confidence = 0.75
|
||||
method = 'text_orientation_heuristic'
|
||||
elif h > w * 1.3:
|
||||
# Portrait image - likely needs rotation
|
||||
top_density = np.mean(binary[:h//4, :])
|
||||
bottom_density = np.mean(binary[3*h//4:, :])
|
||||
|
||||
if top_density > bottom_density * 1.1:
|
||||
rotation_angle = 270
|
||||
else:
|
||||
rotation_angle = 90
|
||||
confidence = 0.7
|
||||
method = 'aspect_ratio_heuristic'
|
||||
else:
|
||||
# Landscape - check if upside down
|
||||
top_density = np.mean(binary[:h//4, :])
|
||||
bottom_density = np.mean(binary[3*h//4:, :])
|
||||
|
||||
if bottom_density > top_density * 1.5:
|
||||
rotation_angle = 180
|
||||
confidence = 0.6
|
||||
else:
|
||||
rotation_angle = 0
|
||||
confidence = 0.8
|
||||
method = 'aspect_ratio_heuristic'
|
||||
|
||||
# Apply rotation
|
||||
img_np = np.array(pil_img.convert('RGB'))
|
||||
corrected_np = self._rotate_exact(img_np, rotation_angle)
|
||||
corrected_pil = Image.fromarray(corrected_np)
|
||||
|
||||
debug_info = {
|
||||
'rotation_angle': rotation_angle,
|
||||
'method': method,
|
||||
'confidence': confidence,
|
||||
'ocr_available': self.ocr_ready
|
||||
}
|
||||
|
||||
return corrected_pil, rotation_angle, debug_info
|
||||
|
||||
|
||||
class ImagePreprocessor:
|
||||
"""
|
||||
Comprehensive image preprocessing for invoice OCR.
|
||||
Handles deskewing, enhancement, and normalization.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.orientation_detector = OrientationDetector()
|
||||
|
||||
@staticmethod
|
||||
def detect_skew(img_np: np.ndarray) -> float:
|
||||
"""Detect skew angle using Hough transform."""
|
||||
gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY) if len(img_np.shape) == 3 else img_np
|
||||
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
|
||||
|
||||
lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=100, minLineLength=100, maxLineGap=10)
|
||||
|
||||
if lines is None:
|
||||
return 0.0
|
||||
|
||||
angles = []
|
||||
for line in lines:
|
||||
x1, y1, x2, y2 = line[0]
|
||||
angle = np.degrees(np.arctan2(y2 - y1, x2 - x1))
|
||||
# Normalize to [-45, 45]
|
||||
if angle < -45:
|
||||
angle += 90
|
||||
if angle > 45:
|
||||
angle -= 90
|
||||
angles.append(angle)
|
||||
|
||||
if not angles:
|
||||
return 0.0
|
||||
|
||||
# Use median to reduce outlier impact
|
||||
median_angle = float(np.median(angles))
|
||||
return median_angle
|
||||
|
||||
@staticmethod
|
||||
def deskew(pil_img: Image.Image, angle: float) -> Image.Image:
|
||||
"""Rotate image to correct skew."""
|
||||
if abs(angle) < 0.1:
|
||||
return pil_img
|
||||
|
||||
# Rotate around center
|
||||
img_np = np.array(pil_img)
|
||||
h, w = img_np.shape[:2]
|
||||
center = (w // 2, h // 2)
|
||||
|
||||
M = cv2.getRotationMatrix2D(center, angle, 1.0)
|
||||
rotated = cv2.warpAffine(
|
||||
img_np, M, (w, h),
|
||||
flags=cv2.INTER_CUBIC,
|
||||
borderMode=cv2.BORDER_REPLICATE
|
||||
)
|
||||
|
||||
return Image.fromarray(rotated)
|
||||
|
||||
@staticmethod
|
||||
def enhance_contrast(pil_img: Image.Image) -> Image.Image:
|
||||
"""
|
||||
Enhance image contrast using CLAHE on the L channel (LAB space).
|
||||
|
||||
Skips enhancement for already-high-contrast images (digital PDFs).
|
||||
Only applies CLAHE when the image stddev indicates a flat histogram
|
||||
(scanned/faded invoices). This avoids amplifying JPEG artifacts on
|
||||
clean digital PDFs.
|
||||
"""
|
||||
img_np = np.array(pil_img.convert('RGB'))
|
||||
gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
|
||||
|
||||
# If contrast is already good (stddev > 60), skip — don't touch clean PDFs
|
||||
if float(np.std(gray)) > 60.0:
|
||||
return pil_img
|
||||
|
||||
# Apply CLAHE to L channel only
|
||||
lab = cv2.cvtColor(img_np, cv2.COLOR_RGB2LAB)
|
||||
l, a, b = cv2.split(lab)
|
||||
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
|
||||
l = clahe.apply(l)
|
||||
lab = cv2.merge([l, a, b])
|
||||
enhanced = cv2.cvtColor(lab, cv2.COLOR_LAB2RGB)
|
||||
return Image.fromarray(enhanced)
|
||||
|
||||
@staticmethod
|
||||
def denoise(pil_img: Image.Image) -> Image.Image:
|
||||
"""Apply denoising filter."""
|
||||
img_np = np.array(pil_img.convert('RGB'))
|
||||
denoised = cv2.fastNlMeansDenoisingColored(img_np, None, 10, 10, 7, 21)
|
||||
return Image.fromarray(denoised)
|
||||
|
||||
@staticmethod
|
||||
def crop_border(pil_img: Image.Image, threshold: int = 240, min_crop: int = 10) -> Image.Image:
|
||||
"""
|
||||
Crop uniform-colored border regions (scanner margins, shadows).
|
||||
|
||||
SAFE VERSION: caps crop at 2% of each dimension to prevent
|
||||
accidentally removing invoice content at edges (dark headers,
|
||||
batch codes near margins, footer totals).
|
||||
"""
|
||||
img_np = np.array(pil_img.convert('RGB'))
|
||||
gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
|
||||
h, w = gray.shape
|
||||
|
||||
# Max 2% of image dimension — prevents content loss
|
||||
max_crop_h = int(h * 0.02)
|
||||
max_crop_w = int(w * 0.02)
|
||||
|
||||
# Sample edge pixels to detect dominant border color
|
||||
edge_pixels = np.concatenate([
|
||||
gray[0, :], # top row
|
||||
gray[-1, :], # bottom row
|
||||
gray[:, 0], # left column
|
||||
gray[:, -1] # right column
|
||||
])
|
||||
edge_median = np.median(edge_pixels)
|
||||
|
||||
# Detect border type: white (>240) or black (<15)
|
||||
if edge_median > threshold:
|
||||
mask = gray < threshold # find dark content in white border
|
||||
else:
|
||||
mask = gray > 15 # find bright content in black border
|
||||
|
||||
rows = np.any(mask, axis=1)
|
||||
cols = np.any(mask, axis=0)
|
||||
|
||||
if not rows.any() or not cols.any():
|
||||
return pil_img
|
||||
|
||||
y_min, y_max = np.where(rows)[0][[0, -1]]
|
||||
x_min, x_max = np.where(cols)[0][[0, -1]]
|
||||
|
||||
# Only crop if detected border is within the safe 2% cap
|
||||
crop_top = min(y_min, max_crop_h) if y_min >= min_crop else 0
|
||||
crop_bottom = max(y_max + 1, h - max_crop_h) if (h - y_max - 1) >= min_crop else h
|
||||
crop_left = min(x_min, max_crop_w) if x_min >= min_crop else 0
|
||||
crop_right = max(x_max + 1, w - max_crop_w) if (w - x_max - 1) >= min_crop else w
|
||||
|
||||
# Safety: never crop more than 2% from any side
|
||||
crop_top = max(crop_top, 0)
|
||||
crop_bottom = min(crop_bottom, h)
|
||||
crop_left = max(crop_left, 0)
|
||||
crop_right = min(crop_right, w)
|
||||
|
||||
cropped = img_np[crop_top:crop_bottom, crop_left:crop_right]
|
||||
return Image.fromarray(cropped)
|
||||
|
||||
@staticmethod
|
||||
def binarize(pil_img: Image.Image) -> Image.Image:
|
||||
"""
|
||||
Adaptive thresholding for low-contrast invoices.
|
||||
|
||||
Converts the image to black text on white background using local
|
||||
threshold adaptation. Useful for faded thermal prints, photocopies,
|
||||
or poorly lit scans where text is washed out.
|
||||
|
||||
Returns:
|
||||
PIL Image (converted back from binary for pipeline compatibility)
|
||||
"""
|
||||
img_np = np.array(pil_img.convert('RGB'))
|
||||
gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
|
||||
|
||||
# Adaptive thresholding: computes local threshold for each 11×11 block
|
||||
# GAUSSIAN: weighs nearby pixels more (smoother than MEAN)
|
||||
# C=2: subtract constant from mean to bias toward text (higher C = more aggressive)
|
||||
binary = cv2.adaptiveThreshold(
|
||||
gray, 255,
|
||||
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
||||
cv2.THRESH_BINARY,
|
||||
blockSize=11,
|
||||
C=2
|
||||
)
|
||||
|
||||
# Convert back to RGB for downstream compatibility
|
||||
rgb = cv2.cvtColor(binary, cv2.COLOR_GRAY2RGB)
|
||||
return Image.fromarray(rgb)
|
||||
|
||||
@staticmethod
|
||||
def sharpen(pil_img: Image.Image) -> Image.Image:
|
||||
"""Sharpen image for better text clarity."""
|
||||
img_np = np.array(pil_img.convert('RGB'))
|
||||
|
||||
# Sharpening kernel
|
||||
kernel = np.array([[-1, -1, -1],
|
||||
[-1, 9, -1],
|
||||
[-1, -1, -1]])
|
||||
|
||||
sharpened = cv2.filter2D(img_np, -1, kernel)
|
||||
return Image.fromarray(sharpened)
|
||||
|
||||
@traceable(name="preprocess_image", tags=["preprocessing"])
|
||||
def process(
|
||||
self,
|
||||
pil_img: Image.Image,
|
||||
do_orient: bool = True,
|
||||
do_deskew: bool = True,
|
||||
do_enhance: bool = True,
|
||||
do_denoise: bool = False,
|
||||
do_sharpen: bool = True,
|
||||
do_crop_border: bool = True,
|
||||
do_binarize: bool = False
|
||||
) -> tuple[Image.Image, dict]:
|
||||
"""
|
||||
Complete preprocessing pipeline.
|
||||
|
||||
Args:
|
||||
pil_img: Input PIL Image
|
||||
do_orient: Correct 0/90/180/270° rotation (via OCR or heuristic)
|
||||
do_deskew: Correct sub-degree skew via Hough transform (recommended ON)
|
||||
do_enhance: CLAHE contrast enhancement on LAB L-channel (recommended ON)
|
||||
do_denoise: Apply color-preserving denoising (slow, use only for noisy scans)
|
||||
do_sharpen: Apply 3x3 sharpening kernel (recommended ON)
|
||||
do_crop_border: Remove scanner margins/shadows (recommended ON)
|
||||
do_binarize: Adaptive thresholding for poor-contrast invoices (use if text is washed out)
|
||||
|
||||
Returns:
|
||||
Tuple of (processed_image, debug_info)
|
||||
"""
|
||||
debug_info = {
|
||||
'original_size': pil_img.size,
|
||||
'steps_applied': []
|
||||
}
|
||||
|
||||
processed = pil_img
|
||||
|
||||
# Step 0: Remove scanner borders/shadows
|
||||
if do_crop_border:
|
||||
processed = self.crop_border(processed)
|
||||
debug_info['steps_applied'].append('Border cropping')
|
||||
|
||||
# Step 1: Orientation correction
|
||||
if do_orient:
|
||||
processed, rotation_angle, orient_debug = self.orientation_detector.detect_and_correct(processed)
|
||||
debug_info['orientation'] = orient_debug
|
||||
debug_info['steps_applied'].append(f'Rotation correction: {rotation_angle}°')
|
||||
|
||||
# Step 2: Skew correction
|
||||
if do_deskew:
|
||||
img_np = np.array(processed.convert('RGB'))
|
||||
skew_angle = self.detect_skew(img_np)
|
||||
if abs(skew_angle) > 0.5:
|
||||
processed = self.deskew(processed, skew_angle)
|
||||
debug_info['skew_angle'] = skew_angle
|
||||
debug_info['steps_applied'].append(f'Deskew: {skew_angle:.2f}°')
|
||||
|
||||
# Step 3: Denoising (optional, can blur text)
|
||||
if do_denoise:
|
||||
processed = self.denoise(processed)
|
||||
debug_info['steps_applied'].append('Denoising')
|
||||
|
||||
# Step 4: Contrast enhancement
|
||||
if do_enhance:
|
||||
processed = self.enhance_contrast(processed)
|
||||
debug_info['steps_applied'].append('Contrast enhancement')
|
||||
|
||||
# Step 5: Sharpening
|
||||
if do_sharpen:
|
||||
processed = self.sharpen(processed)
|
||||
debug_info['steps_applied'].append('Sharpening')
|
||||
|
||||
# Step 6: Binarization (optional)
|
||||
if do_binarize:
|
||||
processed = self.binarize(processed)
|
||||
debug_info['steps_applied'].append('Binarization')
|
||||
|
||||
debug_info['final_size'] = processed.size
|
||||
|
||||
return processed, debug_info
|
||||
|
||||
|
||||
|
||||
@traceable(name="extract_table_region", tags=["preprocessing", "cropping"])
|
||||
def extract_table_region(pil_img: Image.Image, expand_ratio: float = 1.2) -> Image.Image:
|
||||
"""
|
||||
Extract the item table region from invoice for high-resolution batch code extraction.
|
||||
|
||||
Strategy:
|
||||
1. Find horizontal lines (table borders)
|
||||
2. Crop to table region
|
||||
3. Return at FULL resolution for character-level accuracy
|
||||
|
||||
Args:
|
||||
pil_img: Full invoice image
|
||||
expand_ratio: How much to expand detected table region (default 1.2 = 20% padding)
|
||||
|
||||
Returns:
|
||||
Cropped PIL Image containing just the table region at full resolution
|
||||
"""
|
||||
img_np = np.array(pil_img.convert('RGB'))
|
||||
gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
|
||||
h, w = gray.shape
|
||||
|
||||
# Detect horizontal lines (table borders)
|
||||
edges = cv2.Canny(gray, 50, 150)
|
||||
|
||||
# Detect horizontal lines using morphology
|
||||
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (w // 20, 1))
|
||||
horizontal_lines = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, horizontal_kernel)
|
||||
|
||||
# Find contours
|
||||
contours, _ = cv2.findContours(horizontal_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
|
||||
if not contours:
|
||||
print("⚠️ No table detected - returning full image")
|
||||
return pil_img
|
||||
|
||||
# Find the largest rectangular region (likely the table)
|
||||
max_area = 0
|
||||
table_bbox = None
|
||||
|
||||
for contour in contours:
|
||||
x, y, w_box, h_box = cv2.boundingRect(contour)
|
||||
area = w_box * h_box
|
||||
|
||||
# Filter: must be at least 30% of image width and 20% of height
|
||||
if w_box > w * 0.3 and h_box > h * 0.2 and area > max_area:
|
||||
max_area = area
|
||||
table_bbox = (x, y, w_box, h_box)
|
||||
|
||||
if table_bbox is None:
|
||||
print("⚠️ Table region too small - returning full image")
|
||||
return pil_img
|
||||
|
||||
# Expand bbox for safety
|
||||
x, y, w_box, h_box = table_bbox
|
||||
center_x = x + w_box // 2
|
||||
center_y = y + h_box // 2
|
||||
|
||||
new_w = int(w_box * expand_ratio)
|
||||
new_h = int(h_box * expand_ratio)
|
||||
|
||||
x1 = max(0, center_x - new_w // 2)
|
||||
y1 = max(0, center_y - new_h // 2)
|
||||
x2 = min(w, center_x + new_w // 2)
|
||||
y2 = min(h, center_y + new_h // 2)
|
||||
|
||||
# Crop
|
||||
cropped_np = img_np[y1:y2, x1:x2]
|
||||
cropped_pil = Image.fromarray(cropped_np)
|
||||
|
||||
print(f"✂️ Table region extracted: {x1},{y1} → {x2},{y2} ({x2-x1}x{y2-y1})")
|
||||
|
||||
return cropped_pil
|
||||
|
||||
|
||||
@traceable(name="crop_item_rows", tags=["preprocessing", "zoom"])
|
||||
def crop_item_rows(
|
||||
pil_img: Image.Image,
|
||||
n_items: int,
|
||||
zoom_factor: float = 3.0,
|
||||
padding_px: int = 12,
|
||||
table_top_ratio: float = 0.25,
|
||||
table_bottom_ratio: float = 0.92,
|
||||
) -> list[Image.Image]:
|
||||
"""
|
||||
Crop each item row from an invoice table and return zoomed PIL images.
|
||||
|
||||
Strategy
|
||||
--------
|
||||
1. Locate the item-table vertical band by slicing away the header/footer
|
||||
(configurable via table_top_ratio / table_bottom_ratio).
|
||||
2. Find horizontal separators inside that band using ink-density projection:
|
||||
rows with very low horizontal ink are row boundaries.
|
||||
3. Split the band into N row strips (one per item).
|
||||
4. Upscale each strip by zoom_factor (default 3x) using LANCZOS so that
|
||||
4-5 px batch-code characters become 12-15 px — unambiguous for the model.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
pil_img : Full-page preprocessed invoice image.
|
||||
n_items : Expected number of item rows (from first extraction pass).
|
||||
zoom_factor : Upscale multiplier applied to each row crop (default 3.0).
|
||||
padding_px : Extra pixels added above/below each row crop (at original scale).
|
||||
table_top_ratio : Fraction of image height where the item table starts.
|
||||
table_bottom_ratio: Fraction of image height where the item table ends.
|
||||
|
||||
Returns
|
||||
-------
|
||||
List of PIL Images, one per item row, in order.
|
||||
If detection fails or n_items == 0, returns [pil_img] (full image fallback).
|
||||
"""
|
||||
if n_items == 0:
|
||||
return [pil_img]
|
||||
|
||||
img_np = np.array(pil_img.convert('L')) # grayscale numpy
|
||||
full_h, full_w = img_np.shape
|
||||
|
||||
# ── Step 1: restrict to table vertical band ──────────────────────────────
|
||||
y_top = int(full_h * table_top_ratio)
|
||||
y_bottom = int(full_h * table_bottom_ratio)
|
||||
band = img_np[y_top:y_bottom, :]
|
||||
band_h = y_bottom - y_top
|
||||
|
||||
# ── Step 2: ink-density horizontal projection ─────────────────────────────
|
||||
# Invert: white paper = 255 → 0 ink, black text = 0 → 255 ink
|
||||
inv_band = 255 - band
|
||||
row_ink = inv_band.mean(axis=1) # mean ink per horizontal line (float)
|
||||
|
||||
# Smooth slightly to handle dotted/dashed borders
|
||||
kernel_size = max(3, band_h // 80)
|
||||
kernel = np.ones(kernel_size) / kernel_size
|
||||
smoothed = np.convolve(row_ink, kernel, mode='same')
|
||||
|
||||
# ── Step 3: find row boundaries via local minima ──────────────────────────
|
||||
# A boundary is a run of low-ink pixels (border line or gap between rows).
|
||||
ink_threshold = smoothed.max() * 0.15 # below 15% of max = boundary zone
|
||||
is_boundary = smoothed < ink_threshold
|
||||
|
||||
# Convert runs of boundary pixels → single y coordinate (midpoint of run)
|
||||
boundaries = [0] # always start from top of band
|
||||
in_run = False
|
||||
run_start = 0
|
||||
for y, b in enumerate(is_boundary):
|
||||
if b and not in_run:
|
||||
in_run, run_start = True, y
|
||||
elif not b and in_run:
|
||||
boundaries.append((run_start + y) // 2)
|
||||
in_run = False
|
||||
boundaries.append(band_h) # always end at bottom of band
|
||||
|
||||
# Remove duplicates / very close boundaries (< 10px apart)
|
||||
clean_bounds = [boundaries[0]]
|
||||
for b in boundaries[1:]:
|
||||
if b - clean_bounds[-1] > 10:
|
||||
clean_bounds.append(b)
|
||||
|
||||
# ── Step 4: map N items onto detected boundaries ──────────────────────────
|
||||
# If we detected more boundaries than items, we have enough resolution.
|
||||
# If fewer, fall back to equal-height slicing.
|
||||
n_boundaries = len(clean_bounds) - 1 # number of detected intervals
|
||||
|
||||
if n_boundaries >= n_items:
|
||||
# Use detected boundaries directly, merge extras at end if needed
|
||||
row_intervals = []
|
||||
step = n_boundaries / n_items
|
||||
for i in range(n_items):
|
||||
b_start = clean_bounds[int(round(i * step))]
|
||||
b_end = clean_bounds[min(int(round((i + 1) * step)), len(clean_bounds) - 1)]
|
||||
row_intervals.append((b_start, b_end))
|
||||
else:
|
||||
# Equal-height fallback
|
||||
row_h = band_h // n_items
|
||||
row_intervals = [(i * row_h, (i + 1) * row_h) for i in range(n_items)]
|
||||
|
||||
# ── Step 5: crop, pad, zoom each row ─────────────────────────────────────
|
||||
img_rgb = np.array(pil_img.convert('RGB'))
|
||||
crops = []
|
||||
|
||||
for (r_top, r_bot) in row_intervals:
|
||||
# Convert back to full-image coordinates
|
||||
abs_top = max(0, y_top + r_top - padding_px)
|
||||
abs_bot = min(full_h, y_top + r_bot + padding_px)
|
||||
|
||||
row_crop_np = img_rgb[abs_top:abs_bot, :]
|
||||
row_pil = Image.fromarray(row_crop_np)
|
||||
|
||||
# Zoom: upscale to make characters larger
|
||||
new_w = int(row_pil.width * zoom_factor)
|
||||
new_h = int(row_pil.height * zoom_factor)
|
||||
zoomed = row_pil.resize((new_w, new_h), Image.Resampling.LANCZOS)
|
||||
crops.append(zoomed)
|
||||
|
||||
if not crops:
|
||||
print("[crop_item_rows] No rows detected — returning full image")
|
||||
return [pil_img]
|
||||
|
||||
print(f"[crop_item_rows] {len(crops)} row crops at {zoom_factor}x zoom "
|
||||
f"({crops[0].width}x{crops[0].height} each)")
|
||||
return crops
|
||||
@@ -0,0 +1,30 @@
|
||||
# ============================================================
|
||||
# NEW DEPENDENCIES REQUIRED BY THE INTEGRATED MODULES
|
||||
# Append these to your EXISTING requirements.txt.
|
||||
# Do NOT delete or replace your current requirements.txt.
|
||||
# ============================================================
|
||||
|
||||
# REQUIRED — without this, the app will crash on startup with
|
||||
# ModuleNotFoundError. gstin_validator.py, free_item_splitter.py,
|
||||
# ocr_client.py, pdf_utils.py, seller_gstin_lookup.py, and
|
||||
# gst_calculator.py all import `from langsmith import traceable`
|
||||
# at module load time, and app.py imports all of these at the
|
||||
# top of the file with no try/except guard.
|
||||
langsmith>=0.1.0
|
||||
|
||||
# REQUIRED — used by preprocessing.py (ImagePreprocessor: deskew,
|
||||
# orientation correction, contrast/sharpen). app.py already guards
|
||||
# this import in a try/except, so the app itself won't crash if
|
||||
# these are missing, but image preprocessing will silently disable.
|
||||
opencv-python-headless==4.10.0.84
|
||||
numpy==1.26.4
|
||||
scipy==1.13.1
|
||||
|
||||
# ALREADY LIKELY PRESENT — app.py uses `fitz` (PyMuPDF) and
|
||||
# pdf_utils.py needs it too. Only add if not already pinned.
|
||||
pymupdf==1.24.9
|
||||
|
||||
# OPTIONAL — only needed if you later wire in cache_manager.py
|
||||
# (result caching / duplicate detection). NOT currently called
|
||||
# from app.py, so not required today.
|
||||
# imagehash==4.3.1
|
||||
@@ -0,0 +1,19 @@
|
||||
Flask>=3.0.0
|
||||
flask-cors>=4.0.0
|
||||
python-dotenv>=1.0.0
|
||||
requests>=2.31.0
|
||||
pandas>=2.0.0
|
||||
openpyxl>=3.1.0
|
||||
Pillow>=10.0.0
|
||||
PyMuPDF>=1.24.0
|
||||
pdf2image>=1.17.0
|
||||
bcrypt>=4.0.0
|
||||
mysql-connector-python>=8.0.0
|
||||
langsmith>=0.1.0
|
||||
opencv-python-headless>=4.10.0.84
|
||||
numpy>=1.26.4
|
||||
scipy>=1.13.1
|
||||
gunicorn>=21.2.0
|
||||
phonenumbers
|
||||
email-validator
|
||||
email-validator
|
||||
@@ -0,0 +1,96 @@
|
||||
@app.route("/manual-item-codes")
|
||||
def manual_item_codes_page():
|
||||
user_id = session.get("user_id")
|
||||
role = session.get("role")
|
||||
if not user_id or role not in ["user", "dmh"]:
|
||||
return redirect(url_for("login"))
|
||||
return render_template("manual_item_codes.html")
|
||||
|
||||
|
||||
@app.route("/api/manual-extract", methods=["POST"])
|
||||
def api_manual_extract():
|
||||
"""JSON upload endpoint for the Manual Item Codes page. Extracts the
|
||||
invoice, saves it to extraction_history like /upload_image does, and
|
||||
returns the extraction id so the page can save item codes against it."""
|
||||
user_id = session.get("user_id")
|
||||
role = session.get("role")
|
||||
if not user_id or role not in ["user", "dmh"]:
|
||||
return jsonify({"error": "Unauthorized"}), 401
|
||||
|
||||
file = request.files.get("file")
|
||||
if not file or not allowed_file(file.filename):
|
||||
return jsonify({"success": False, "error": "Invalid file. Upload PDF or Image."}), 400
|
||||
|
||||
use_drug_list = request.form.get("use_drug_list", "true").strip().lower() != "false"
|
||||
|
||||
original_filename = secure_filename(file.filename)
|
||||
unique_filename = f"{uuid.uuid4()}_{original_filename}"
|
||||
file_path = os.path.join(app.config["UPLOAD_FOLDER"], unique_filename)
|
||||
file.save(file_path)
|
||||
|
||||
try:
|
||||
ext = original_filename.lower()
|
||||
invoice_source = "manual" if ext.endswith((".jpg", ".jpeg", ".png")) else "email"
|
||||
is_dmh = (role == "dmh")
|
||||
|
||||
extracted_data = extract_invoice_fields(
|
||||
file_path, invoice_source, is_dmh=is_dmh, use_drug_list=use_drug_list
|
||||
)
|
||||
|
||||
if not extracted_data or "error" in extracted_data:
|
||||
err = extracted_data.get("error", "Extraction failed") if isinstance(extracted_data, dict) else "Extraction failed"
|
||||
return jsonify({"success": False, "error": err}), 400
|
||||
|
||||
invoice_id = extracted_data.get("invoice_id")
|
||||
|
||||
# Pull billing metadata out before saving the JSON, same as /upload_image
|
||||
_input_tokens = extracted_data.pop("_input_tokens", 0)
|
||||
_output_tokens = extracted_data.pop("_output_tokens", 0)
|
||||
_cost_usd = extracted_data.pop("_cost_usd", 0.0)
|
||||
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
cursor.execute(
|
||||
"UPDATE users SET invoices_extracted = invoices_extracted + 1 WHERE username = %s",
|
||||
(session["user"],),
|
||||
)
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO extraction_history
|
||||
(invoice_id, invoice_source, user_id, timestamp, image_name, pages_extracted,
|
||||
extraction_type, extracted_data, file_path, input_tokens, output_tokens, cost_usd)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
""",
|
||||
(
|
||||
invoice_id,
|
||||
invoice_source,
|
||||
user_id,
|
||||
datetime.now(),
|
||||
original_filename,
|
||||
len(extracted_data.get("items", [])),
|
||||
"invoice",
|
||||
json.dumps(extracted_data),
|
||||
file_path,
|
||||
_input_tokens,
|
||||
_output_tokens,
|
||||
_cost_usd,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
extraction_id = cursor.lastrowid
|
||||
finally:
|
||||
cursor.close()
|
||||
conn.close()
|
||||
|
||||
return jsonify({"success": True, "data": extracted_data, "extraction_id": extraction_id}), 200
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Manual-extract error: {e}", exc_info=True)
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
finally:
|
||||
try:
|
||||
if os.path.exists(file_path):
|
||||
os.remove(file_path)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,548 @@
|
||||
"""
|
||||
Vendor Master & GSTIN Lookup (Dynamic Excel-backed)
|
||||
---------------------------------------------------
|
||||
Uses 'Seller_GSTIN.xlsx' as the authoritative vendor master.
|
||||
|
||||
Features:
|
||||
1. Loads all approved vendors, supplier codes, and GSTINs on startup.
|
||||
2. Multi-tier matching (exact, alias, substring, token overlap) to find
|
||||
the authoritative GSTIN even with OCR typos in the invoice vendor name.
|
||||
3. If a vendor is found: overrides/enriches seller_gstin with the authoritative GSTIN.
|
||||
4. If a vendor is NOT found:
|
||||
- Extracts and shows the vendor name & GSTIN from OCR.
|
||||
- Automatically appends the new vendor to 'Seller_GSTIN.xlsx'
|
||||
so future invoices will recognize it immediately.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
if hasattr(sys.stdout, 'reconfigure'):
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding='utf-8')
|
||||
except Exception:
|
||||
pass
|
||||
if hasattr(sys.stderr, 'reconfigure'):
|
||||
try:
|
||||
sys.stderr.reconfigure(encoding='utf-8')
|
||||
except Exception:
|
||||
pass
|
||||
import re
|
||||
import unicodedata
|
||||
import threading
|
||||
from typing import Optional, Dict, Any, List
|
||||
import openpyxl
|
||||
|
||||
try:
|
||||
from langsmith import traceable
|
||||
except ImportError:
|
||||
def traceable(*args, **kwargs):
|
||||
def decorator(fn):
|
||||
return fn
|
||||
return decorator
|
||||
|
||||
try:
|
||||
from gstin_validator import validate_and_fix_gstin
|
||||
except ImportError:
|
||||
def validate_and_fix_gstin(raw, label='GSTIN'):
|
||||
if not raw:
|
||||
return None
|
||||
cleaned = re.sub(r'[\s\-\./]', '', str(raw)).upper()
|
||||
return cleaned
|
||||
|
||||
# Thread safety lock for reading/writing the vendor Excel file
|
||||
_EXCEL_LOCK = threading.Lock()
|
||||
|
||||
# Candidate filenames for the vendor master sheet
|
||||
VENDOR_EXCEL_CANDIDATES = [
|
||||
"Seller_GSTIN.xlsx",
|
||||
"LIST OF VENDOR WITH GST.xlsx",
|
||||
"LIST OF VENDOR WITH GST (1).xlsx",
|
||||
"list of vendor.xlsx",
|
||||
"list of vendor .xlsx",
|
||||
]
|
||||
|
||||
_VENDOR_FILE_PATH: Optional[str] = None
|
||||
_VENDOR_ENTRIES: List[Dict[str, Any]] = []
|
||||
_VENDOR_LOOKUP: Dict[str, Dict[str, Any]] = {}
|
||||
_LAST_LOAD_TIME: float = 0
|
||||
|
||||
|
||||
# Stop words to ignore during fuzzy token matching
|
||||
_STOP_WORDS = {
|
||||
"PVT", "LTD", "LIMITED", "PRIVATE", "LLP", "ENTERPRISES", "ENTERPRISE",
|
||||
"SERVICES", "PHARMA", "PHARMACEUTICALS", "PHARMACEUTICAL", "CORPORATION",
|
||||
"DISTRIBUTORS", "DISTRIBUTOR", "AGENCIES", "AGENCY", "MEDISALES", "HEALTHCARE",
|
||||
"SOLUTIONS", "MARKETING", "LIFE", "SCIENCES", "LIFESCIENCES", "MEDICAL",
|
||||
"STORE", "STORES", "AND", "&", "CO", "COMPANY", "INDIA"
|
||||
}
|
||||
|
||||
# Known aliases and edge-case overrides
|
||||
SELLER_GSTIN_MAP: Dict[str, str] = {
|
||||
"PHARMACEA LINK": "27AALFP5376P1ZA",
|
||||
"PHARMACEALINK": "27AALFP5376P1ZA",
|
||||
"AADESH PHARMACEUTICAL": "27ABLFA7017P1ZX",
|
||||
"AADESH PHARMACEUUTICAL": "27ABLFA7017P1ZX",
|
||||
"AADESH PHARMACEUTICALS": "27ABLFA7017P1ZX",
|
||||
"PROGRESS HEALTHCARE MEDICAL SERVICES LLP": "27AAVFP0728M1ZK",
|
||||
"PROGRESS HEALTHCARE & MEDICAL SERVICES LLP": "27AAVFP0728M1ZK",
|
||||
"SHLOKA ENTERPRISES": "27AIWPA8054A1ZA",
|
||||
"CRITICAL CARE SYSTEMS": "27AADFC3319B1Z1",
|
||||
"HEALTHCARE ENTERPRISES": "27AFTPK0484L1ZT",
|
||||
"KALPAK MARKETING PVT LTD": "27AABCK2267K1ZD",
|
||||
"KALPAK MARKETING PRIVATE LIMITED": "27AABCK2267K1ZD",
|
||||
"AVIAN WELLNESS PVT LTD": "27AAOCA5119K1ZD",
|
||||
"AVIAN WELLNESS PVTLTD": "27AAOCA5119K1ZD",
|
||||
"AVIAN WELLNESS PRIVATE LIMITED": "27AAOCA5119K1ZD",
|
||||
"NEW SALAKSHMI MEDISALES LLP": "27AAOFN3880H1ZT",
|
||||
"TAPADIYA DISTRIBUTORS": "27AABFT1696C1Z8",
|
||||
"AAKANKSHA LOGISTICS PVT LTD": "27AACCA2971K1ZJ",
|
||||
"AAKANKSHA LOGISTICS PRIVATE LIMITED": "27AACCA2971K1ZJ",
|
||||
"KANCHAN DRUGS PRIVATE LIMITED": "27AAACK7501K1ZJ",
|
||||
"KANCHAN DRUGS PVT LTD": "27AAACK7501K1ZJ",
|
||||
"SAIRAJ DISTRIBUTORS": "27ADLFS9893D1ZC",
|
||||
"MILTON LIFECARE PRIVATE LIMITED": "27AAFCM2670J1ZA",
|
||||
"MILTON LIFECARE PVT LTD": "27AAFCM2670J1ZA",
|
||||
"KUNDAN DISTRIBUTORS PVT LTD": "27AAHCK2490E1ZJ",
|
||||
"KUNDAN DISTRIBUTORS PRIVATE LIMITED": "27AAHCK2490E1ZJ",
|
||||
"NITIN AGENCY PHARMACEUTICAL DISTRIBUTORS": "27AACFN3926C1ZK",
|
||||
"NITIN AGENCY": "27AACFN3926C1ZK",
|
||||
"YOGA ENTERPRISES": "27AAZPP8101A1ZL",
|
||||
"SCORIA INCORPORATION": "27AAUPD9798E1ZX",
|
||||
"ARIHANT BIOPHARMA CORPORATION": "27AAJFA9526G1ZA",
|
||||
"CHEMSEARCH": "27AAIFC6533C1ZO",
|
||||
"SPANDAN HEALTHCARE": "27AFIPD4405P1ZA",
|
||||
"MATRIX BIOMEDICS PVT LTD": "27AADCM2647P1ZZ",
|
||||
"MATRIX BIOMEDICS PRIVATE LIMITED": "27AADCM2647P1ZZ",
|
||||
"SANJEEVANI ENTERPRISE 25 26": "27ACDFS6564Q1Z9",
|
||||
"SANJEEVANI ENTERPRISE 2526": "27ACDFS6564Q1Z9",
|
||||
"SANJEEVANI ENTERPRISE": "27ACDFS6564Q1Z9",
|
||||
"ARIHANT CHEMIST LLP": "27ABLFA7907J1Z2",
|
||||
"TAPADIYA LIFE SCIENCES": "27AAFFT4132P1ZS",
|
||||
"E BIOREMEDIES LTD": "27AADCE3683M1Z7",
|
||||
"E BIOREMEDIES LIMITED": "27AADCE3683M1Z7",
|
||||
"ONENESS ENTERPRISES": "27BGMPM8256M1ZJ",
|
||||
"ONENESS ENTERPRISES FY 2025 26": "27BGMPM8256M1ZJ",
|
||||
"ONENESS ENTERPRISES FY 202526": "27BGMPM8256M1ZJ",
|
||||
"VIHAAN ENTERPRISES": "27AAVPP4610L1Z4",
|
||||
"PRANAV MEDICARE 2025 2027": "27AUVPS6762N1ZB",
|
||||
"PRANAV MEDICARE 2025 2026": "27AUVPS6762N1ZB",
|
||||
"PRANAV MEDICARE": "27AUVPS6762N1ZB",
|
||||
"DEENANATH MEDICAL STORES": "27AAATL1944N1ZA",
|
||||
"RAVI MEDICO": "27AAUPR1161Q1ZD",
|
||||
"GALAXY ALLIANCE LLP": "27AAYFG6456C1ZY",
|
||||
"MIS HEALTHCARE PVT LTD": "27AAHCM2065M1Z5",
|
||||
"MIS HEALTHCARE PRIVATE LIMITED": "27AAHCM2065M1Z5",
|
||||
"HEALTHLINE PRIVATE LIMITED": "29AABCH3719P1ZU",
|
||||
"HEALTHLINE PVT LTD": "29AABCH3719P1ZU",
|
||||
"ASSOCIATED THERAPEUTIC CARE PVT LTD": "27AALCA3876G1ZD",
|
||||
"ASSOCIATED THERAPEUTIC CARE PRIVATE LIMITED": "27AALCA3876G1ZD",
|
||||
"SHREE VENKATESH AGENCIES": "27ACSFS1246C1Z2",
|
||||
"KDB SURGI PHARMA": "27AAIFK8419R1ZG",
|
||||
"KDB SURGIPHARMA": "27AAIFK8419R1ZG",
|
||||
"CHANDULAL R MEHTA": "27AAKPC8047A1ZB",
|
||||
}
|
||||
|
||||
|
||||
def _find_vendor_file() -> Optional[str]:
|
||||
"""Find the path of the vendor master Excel file."""
|
||||
base_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
for candidate in VENDOR_EXCEL_CANDIDATES:
|
||||
full_path = os.path.join(base_dir, candidate)
|
||||
if os.path.exists(full_path):
|
||||
return full_path
|
||||
|
||||
# Check parent directory as fallback
|
||||
parent_dir = os.path.dirname(base_dir)
|
||||
for candidate in VENDOR_EXCEL_CANDIDATES:
|
||||
full_path = os.path.join(parent_dir, candidate)
|
||||
if os.path.exists(full_path):
|
||||
return full_path
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _normalise(name: str) -> str:
|
||||
"""
|
||||
UPPERCASE, strip diacritics (ä→a, etc.), collapse whitespace,
|
||||
strip punctuation so minor OCR variations still match.
|
||||
"""
|
||||
if not name:
|
||||
return ""
|
||||
name = unicodedata.normalize('NFKD', str(name))
|
||||
name = ''.join(c for c in name if not unicodedata.combining(c))
|
||||
name = name.upper()
|
||||
name = re.sub(r"[.\-,&'/\\]", " ", name)
|
||||
name = re.sub(r"\s+", " ", name).strip()
|
||||
return name
|
||||
|
||||
|
||||
def _significant_tokens(norm_name: str) -> set:
|
||||
"""Extract significant tokens ignoring common stop words."""
|
||||
tokens = {t for t in norm_name.split() if len(t) > 1 and t not in _STOP_WORDS}
|
||||
return tokens
|
||||
|
||||
|
||||
def load_vendor_master_excel(force: bool = False) -> None:
|
||||
"""
|
||||
Load approved vendors from the Excel master file into in-memory lookup.
|
||||
"""
|
||||
global _VENDOR_FILE_PATH, _VENDOR_ENTRIES, _VENDOR_LOOKUP, _LAST_LOAD_TIME
|
||||
with _EXCEL_LOCK:
|
||||
file_path = _find_vendor_file()
|
||||
if not file_path:
|
||||
print("⚠️ Vendor master Excel file not found. Falling back to built-in vendor map.")
|
||||
_VENDOR_FILE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "Seller_GSTIN.xlsx")
|
||||
return
|
||||
|
||||
_VENDOR_FILE_PATH = file_path
|
||||
try:
|
||||
# Load with data_only=True to evaluate formulas like =VLOOKUP(...)
|
||||
wb = openpyxl.load_workbook(file_path, data_only=True)
|
||||
ws = wb.active
|
||||
|
||||
# Detect header row and column positions
|
||||
header_row = None
|
||||
name_col = None
|
||||
gst_col = None
|
||||
sr_col = None
|
||||
code_col = None
|
||||
|
||||
for r in range(1, min(10, ws.max_row + 1)):
|
||||
row_vals = [str(ws.cell(r, c).value or '').strip().upper() for c in range(1, max(ws.max_column + 1, 10))]
|
||||
has_vendor = any("VENDOR" in v or "NAME" in v for v in row_vals)
|
||||
has_gst = any("GST" in v for v in row_vals)
|
||||
if has_vendor or has_gst:
|
||||
header_row = r
|
||||
for c_idx, val in enumerate(row_vals, start=1):
|
||||
if "GST" in val and not gst_col:
|
||||
gst_col = c_idx
|
||||
elif ("VENDOR" in val or "NAME" in val) and not name_col:
|
||||
name_col = c_idx
|
||||
elif ("SR" in val or "S.NO" in val) and not sr_col:
|
||||
sr_col = c_idx
|
||||
elif "CODE" in val and not code_col:
|
||||
code_col = c_idx
|
||||
if name_col and gst_col:
|
||||
break
|
||||
|
||||
if not header_row:
|
||||
header_row = 2
|
||||
|
||||
# Fallbacks if columns not identified by headers
|
||||
if not name_col and not gst_col:
|
||||
name_col, gst_col = 1, 2
|
||||
|
||||
# Prevent column overlap
|
||||
if sr_col in (name_col, gst_col):
|
||||
sr_col = None
|
||||
if code_col in (name_col, gst_col):
|
||||
code_col = None
|
||||
|
||||
entries = []
|
||||
lookup = {}
|
||||
|
||||
for r in range(header_row + 1, ws.max_row + 1):
|
||||
sr_val = ws.cell(r, sr_col).value if sr_col else None
|
||||
code_val = ws.cell(r, code_col).value if code_col else None
|
||||
name_val = ws.cell(r, name_col).value if name_col else None
|
||||
gst_val = ws.cell(r, gst_col).value if gst_col else None
|
||||
|
||||
if not name_val:
|
||||
continue
|
||||
|
||||
raw_name = str(name_val or "").strip()
|
||||
if not raw_name:
|
||||
continue
|
||||
|
||||
raw_gstin = str(gst_val or "").strip().upper()
|
||||
if raw_gstin in ("NONE", "NAN", "NULL"):
|
||||
raw_gstin = ""
|
||||
|
||||
# Clean GSTIN
|
||||
clean_gstin = re.sub(r'[^A-Z0-9]', '', raw_gstin)
|
||||
|
||||
entry = {
|
||||
"row_index": r,
|
||||
"sr_no": sr_val,
|
||||
"supplier_code": str(code_val or "").strip() if code_val else "",
|
||||
"name": raw_name,
|
||||
"norm_name": _normalise(raw_name),
|
||||
"gstin": clean_gstin,
|
||||
}
|
||||
entries.append(entry)
|
||||
|
||||
if entry["norm_name"]:
|
||||
lookup[entry["norm_name"]] = entry
|
||||
|
||||
# Also seed any SELLER_GSTIN_MAP entries if not present
|
||||
for alias_name, gstin in SELLER_GSTIN_MAP.items():
|
||||
norm_alias = _normalise(alias_name)
|
||||
if norm_alias not in lookup:
|
||||
lookup[norm_alias] = {
|
||||
"row_index": None,
|
||||
"sr_no": None,
|
||||
"supplier_code": "MAP",
|
||||
"name": alias_name,
|
||||
"norm_name": norm_alias,
|
||||
"gstin": gstin,
|
||||
}
|
||||
|
||||
_VENDOR_ENTRIES = entries
|
||||
_VENDOR_LOOKUP = lookup
|
||||
_LAST_LOAD_TIME = os.path.getmtime(file_path) if os.path.exists(file_path) else 0
|
||||
|
||||
print(f"✅ Vendor master loaded: {len(entries)} vendors from '{os.path.basename(file_path)}' (lookup keys: {len(lookup)})")
|
||||
except Exception as e:
|
||||
print(f"⚠️ Error loading vendor master Excel ({file_path}): {e}")
|
||||
|
||||
|
||||
def lookup_vendor(seller_name: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Search for a vendor in the vendor master.
|
||||
Matching Strategy:
|
||||
1. Exact normalized name match.
|
||||
2. Known alias / SELLER_GSTIN_MAP match.
|
||||
3. Substring match: lookup key inside seller_name, or seller_name inside lookup key.
|
||||
4. Significant token overlap match.
|
||||
"""
|
||||
if not seller_name:
|
||||
return None
|
||||
|
||||
if not _VENDOR_LOOKUP:
|
||||
load_vendor_master_excel()
|
||||
|
||||
norm_query = _normalise(seller_name)
|
||||
if not norm_query:
|
||||
return None
|
||||
|
||||
# 1. Exact normalized match
|
||||
if norm_query in _VENDOR_LOOKUP:
|
||||
return _VENDOR_LOOKUP[norm_query]
|
||||
|
||||
# 2. Check SELLER_GSTIN_MAP direct match
|
||||
if norm_query in SELLER_GSTIN_MAP:
|
||||
return {"name": seller_name, "gstin": SELLER_GSTIN_MAP[norm_query], "supplier_code": "MAP"}
|
||||
|
||||
# 3. Substring matching
|
||||
# Best substring: prefer candidate with maximum length match
|
||||
best_candidate = None
|
||||
best_match_len = 0
|
||||
|
||||
for norm_key, entry in _VENDOR_LOOKUP.items():
|
||||
if len(norm_key) < 3:
|
||||
continue
|
||||
# Key is inside extracted name (e.g. "KANCHAN DRUGS" in "KANCHAN DRUGS PRIVATE LIMITED")
|
||||
if norm_key in norm_query:
|
||||
if len(norm_key) > best_match_len:
|
||||
best_match_len = len(norm_key)
|
||||
best_candidate = entry
|
||||
# Extracted name is inside Key
|
||||
elif norm_query in norm_key and len(norm_query) >= 4:
|
||||
if len(norm_query) > best_match_len:
|
||||
best_match_len = len(norm_query)
|
||||
best_candidate = entry
|
||||
|
||||
if best_candidate:
|
||||
return best_candidate
|
||||
|
||||
# 4. Token overlap matching
|
||||
query_tokens = _significant_tokens(norm_query)
|
||||
if len(query_tokens) >= 2:
|
||||
for norm_key, entry in _VENDOR_LOOKUP.items():
|
||||
entry_tokens = _significant_tokens(norm_key)
|
||||
if entry_tokens and (query_tokens.issubset(entry_tokens) or entry_tokens.issubset(query_tokens)):
|
||||
return entry
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def lookup_seller_gstin(seller_name: str) -> Optional[str]:
|
||||
"""
|
||||
Backwards-compatible function: returns just the GSTIN string for *seller_name*,
|
||||
or None if not found in the vendor master.
|
||||
"""
|
||||
match = lookup_vendor(seller_name)
|
||||
return match.get("gstin") if match else None
|
||||
|
||||
|
||||
def add_vendor_to_excel(seller_name: str, gstin: str, supplier_code: Optional[str] = None) -> bool:
|
||||
"""
|
||||
Dynamically append a new vendor and GSTIN into the Excel master file.
|
||||
Also updates in-memory cache immediately.
|
||||
"""
|
||||
clean_name = str(seller_name or "").strip()
|
||||
if not clean_name or len(clean_name) < 3:
|
||||
return False
|
||||
|
||||
# Ignore obvious invoice header false positives
|
||||
generic_false_positives = {
|
||||
"TAX INVOICE", "INVOICE", "BILL OF SUPPLY", "ORIGINAL FOR RECIPIENT",
|
||||
"DUPLICATE FOR TRANSPORTER", "PURCHASE ORDER", "CASH MEMO", "RETAIL INVOICE"
|
||||
}
|
||||
if _normalise(clean_name) in generic_false_positives:
|
||||
return False
|
||||
|
||||
clean_gstin = re.sub(r'[^A-Z0-9]', '', str(gstin or "").upper())
|
||||
|
||||
with _EXCEL_LOCK:
|
||||
file_path = _VENDOR_FILE_PATH or _find_vendor_file()
|
||||
if not file_path:
|
||||
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "Seller_GSTIN.xlsx")
|
||||
|
||||
norm_name = _normalise(clean_name)
|
||||
if norm_name in _VENDOR_LOOKUP:
|
||||
existing = _VENDOR_LOOKUP[norm_name]
|
||||
if existing.get("gstin"):
|
||||
print(f"[VENDOR EXCEL] Vendor '{clean_name}' already exists with GSTIN '{existing.get('gstin')}'. Skipping duplicate addition.")
|
||||
return False
|
||||
|
||||
try:
|
||||
wb = openpyxl.load_workbook(file_path, data_only=False)
|
||||
ws = wb.active
|
||||
|
||||
# Detect column positions in worksheet
|
||||
name_col = None
|
||||
gst_col = None
|
||||
sr_col = None
|
||||
code_col = None
|
||||
|
||||
for r in range(1, min(10, ws.max_row + 1)):
|
||||
row_vals = [str(ws.cell(r, c).value or '').strip().upper() for c in range(1, max(ws.max_column + 1, 10))]
|
||||
has_vendor = any("VENDOR" in v or "NAME" in v for v in row_vals)
|
||||
has_gst = any("GST" in v for v in row_vals)
|
||||
if has_vendor or has_gst:
|
||||
for c_idx, val in enumerate(row_vals, start=1):
|
||||
if "GST" in val and not gst_col:
|
||||
gst_col = c_idx
|
||||
elif ("VENDOR" in val or "NAME" in val) and not name_col:
|
||||
name_col = c_idx
|
||||
elif ("SR" in val or "S.NO" in val) and not sr_col:
|
||||
sr_col = c_idx
|
||||
elif "CODE" in val and not code_col:
|
||||
code_col = c_idx
|
||||
if name_col and gst_col:
|
||||
break
|
||||
|
||||
if not name_col and not gst_col:
|
||||
name_col, gst_col = 1, 2
|
||||
|
||||
# Prevent column overlap
|
||||
if sr_col in (name_col, gst_col):
|
||||
sr_col = None
|
||||
if code_col in (name_col, gst_col):
|
||||
code_col = None
|
||||
|
||||
# Find true last row
|
||||
last_row = 2
|
||||
max_sr = 0
|
||||
for r in range(2, ws.max_row + 1):
|
||||
val_sr = ws.cell(r, sr_col).value if sr_col else None
|
||||
val_name = ws.cell(r, name_col).value if name_col else None
|
||||
if val_sr is not None or val_name is not None:
|
||||
last_row = r
|
||||
try:
|
||||
if val_sr and int(val_sr) > max_sr:
|
||||
max_sr = int(val_sr)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
new_row = last_row + 1
|
||||
new_sr = max_sr + 1 if sr_col else None
|
||||
code = supplier_code or (f"S-AUTO{new_sr}" if new_sr else "")
|
||||
|
||||
if sr_col:
|
||||
ws.cell(new_row, sr_col, new_sr)
|
||||
if code_col:
|
||||
ws.cell(new_row, code_col, code)
|
||||
ws.cell(new_row, name_col, clean_name)
|
||||
ws.cell(new_row, gst_col, clean_gstin)
|
||||
|
||||
wb.save(file_path)
|
||||
|
||||
# Update in-memory entries
|
||||
new_entry = {
|
||||
"row_index": new_row,
|
||||
"sr_no": new_sr,
|
||||
"supplier_code": code,
|
||||
"name": clean_name,
|
||||
"norm_name": norm_name,
|
||||
"gstin": clean_gstin,
|
||||
}
|
||||
_VENDOR_ENTRIES.append(new_entry)
|
||||
_VENDOR_LOOKUP[norm_name] = new_entry
|
||||
|
||||
print(f"💾 [VENDOR EXCEL] Successfully appended new vendor to '{os.path.basename(file_path)}':")
|
||||
print(f" Row: {new_row} | SR: {new_sr} | Code: {code} | Name: '{clean_name}' | GSTIN: '{clean_gstin}'")
|
||||
return True
|
||||
|
||||
except PermissionError:
|
||||
print(f"⚠️ [VENDOR EXCEL] Could not write to '{file_path}' (file is open in another program like Excel).")
|
||||
# Keep in-memory so subsequent queries still benefit
|
||||
new_entry = {
|
||||
"row_index": None,
|
||||
"sr_no": None,
|
||||
"supplier_code": supplier_code or "S-AUTO",
|
||||
"name": clean_name,
|
||||
"norm_name": norm_name,
|
||||
"gstin": clean_gstin,
|
||||
}
|
||||
_VENDOR_LOOKUP[norm_name] = new_entry
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"⚠️ [VENDOR EXCEL] Failed to append vendor to Excel: {e}")
|
||||
return False
|
||||
|
||||
|
||||
@traceable(name="apply_seller_gstin_override", tags=["override", "seller-gstin"])
|
||||
def apply_seller_gstin_override(data: dict) -> dict:
|
||||
"""
|
||||
Checks the vendor name against the vendor master Excel file ('Seller_GSTIN.xlsx'):
|
||||
1. If found in the Excel file:
|
||||
- Fetches authoritative GSTIN from Excel and overrides data['seller_gstin'].
|
||||
- Also fills or updates vendor details.
|
||||
2. If NOT found in the Excel file:
|
||||
- Retains the OCR-extracted seller_name and seller_gstin for display.
|
||||
- Automatically appends the new vendor to the Excel file so it's remembered.
|
||||
"""
|
||||
seller_name = (data.get("seller_name") or "").strip()
|
||||
extracted_gstin = (data.get("seller_gstin") or "").strip()
|
||||
|
||||
if not seller_name:
|
||||
return data
|
||||
|
||||
match = lookup_vendor(seller_name)
|
||||
|
||||
if match and match.get("gstin"):
|
||||
authoritative_gstin = match["gstin"]
|
||||
canonical_name = match.get("name") or seller_name
|
||||
|
||||
if extracted_gstin == authoritative_gstin:
|
||||
print(f"[VENDOR EXCEL] ✅ Verified in Excel: '{seller_name}' -> {authoritative_gstin}")
|
||||
else:
|
||||
print(f"[VENDOR EXCEL] 🔧 Found in Excel for '{seller_name}'. Overriding GSTIN:")
|
||||
print(f" Extracted : '{extracted_gstin}'")
|
||||
print(f" Excel GSTIN: '{authoritative_gstin}' ({canonical_name})")
|
||||
data["seller_gstin"] = authoritative_gstin
|
||||
|
||||
# Optionally enrich canonical name if not empty
|
||||
if canonical_name and not data.get("seller_name"):
|
||||
data["seller_name"] = canonical_name
|
||||
|
||||
else:
|
||||
# Vendor not found in the Excel file!
|
||||
print(f"[VENDOR EXCEL] 🔍 Vendor '{seller_name}' not in Excel file. Preserving OCR extraction.")
|
||||
|
||||
# Clean/validate extracted GSTIN
|
||||
clean_extracted_gstin = ""
|
||||
if extracted_gstin:
|
||||
clean_extracted_gstin = validate_and_fix_gstin(extracted_gstin, label="NewSeller") or extracted_gstin
|
||||
data["seller_gstin"] = clean_extracted_gstin
|
||||
|
||||
# Store to Excel file dynamically
|
||||
add_vendor_to_excel(seller_name=seller_name, gstin=clean_extracted_gstin)
|
||||
|
||||
return data
|
||||
|
||||
|
||||
# Auto-load on initial import
|
||||
load_vendor_master_excel()
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 50 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 252 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.1 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 65 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.4 KiB |
@@ -0,0 +1,129 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="description" content="Learn about AI Infinite - Empowering businesses with AI-driven document processing and data extraction." />
|
||||
<meta name="keywords" content="AI Infinite, about us, document processing, data extraction, AI automation" />
|
||||
<title>About Us - AI Infinite</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
|
||||
<link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
|
||||
<link rel="icon" href="{{ url_for('static', filename='logos/ai infinite.jpg') }}" type="image/x-icon">
|
||||
</head>
|
||||
<body class="antialiased text-gray-800 font-sans">
|
||||
<!-- Navigation (matched to Invoice page) -->
|
||||
<!-- Updated Navbar -->
|
||||
<nav id="navbar" class="fixed top-0 left-0 w-full bg-[#f7f7f7] backdrop-blur shadow-md z-50">
|
||||
<div class="container mx-auto px-6 py-4 flex items-center">
|
||||
<!-- Logo / Brand -->
|
||||
<a href="{{ url_for('home_logged_in') if logged_in else url_for('index') }}" class="flex items-center space-x-2 hover:opacity-90">
|
||||
<img src="{{ url_for('static', filename='logos/aiinfinite.png') }}" alt="AI Infinite Logo" class="h-12 md:h-16 w-auto" />
|
||||
<span class="text-xl font-bold text-gray-800"></span>
|
||||
</a>
|
||||
|
||||
<!-- Combined Right-side Links -->
|
||||
<div class="hidden md:flex items-center ml-auto space-x-12">
|
||||
<a href="{{ url_for('invoice', doc_type='invoice') }}" class="text-gray-700 hover:text-blue-600 font-medium">Invoice</a>
|
||||
<a href="{{ url_for('passport', doc_type='passport') }}" class="text-gray-700 hover:text-blue-600 font-medium">Passport</a>
|
||||
<a href="{{ url_for('pricing') }}" class="text-gray-700 hover:text-blue-600 font-medium">Pricing</a>
|
||||
<a href="{{ url_for('about') }}" class="text-gray-700 hover:text-blue-600 font-medium">About</a>
|
||||
{% if logged_in %}
|
||||
<a href="{{ url_for('dashboard') }}" class="text-gray-700 hover:text-blue-600 font-medium">Dashboard</a>
|
||||
<a href="{{ url_for('logout') }}" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg font-semibold">Logout</a>
|
||||
{% else %}
|
||||
<a href="{{ url_for('login') }}" class="text-gray-700 hover:text-blue-600 font-medium">Log in</a>
|
||||
<a href="{{ url_for('login') }}" class="bg-blue-600 hover:bg-blue-700 text-white px-5 py-2 rounded-lg font-semibold">Get Started</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- Mobile Menu Button -->
|
||||
<button id="menu-btn" class="md:hidden text-gray-700 focus:outline-none">
|
||||
<i class="fas fa-bars fa-2x"></i>
|
||||
</button>
|
||||
</div>
|
||||
<!-- Mobile Menu Content -->
|
||||
<div id="menu" class="hidden md:hidden bg-[#f7f7f7] backdrop-blur shadow-inner">
|
||||
<div class="flex flex-col space-y-2 px-6 py-4">
|
||||
<a href="{{ url_for('invoice', doc_type='invoice') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Invoice</a>
|
||||
<a href="{{ url_for('passport', doc_type='passport') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Passport</a>
|
||||
<a href="{{ url_for('pricing') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Pricing</a>
|
||||
<a href="{{ url_for('about') }}" class="block text-gray-700 hover:text-blue-600 font-medium">About</a>
|
||||
{% if logged_in %}
|
||||
<a href="{{ url_for('dashboard') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Dashboard</a>
|
||||
<a href="{{ url_for('logout') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Logout</a>
|
||||
{% else %}
|
||||
<a href="{{ url_for('login') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Log in</a>
|
||||
<a href="{{ url_for('login') }}" class="block bg-blue-600 hover:bg-blue-700 text-white px-5 py-2 rounded-lg font-semibold text-center">Get Started</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<!-- Main Content -->
|
||||
<section class="py-24 bg-gray-50 mt-16">
|
||||
<div class="container mx-auto px-6 space-y-20">
|
||||
|
||||
<!-- What We Do -->
|
||||
<div data-aos="fade-up">
|
||||
<h2 class="text-4xl font-bold text-center mb-6">What We Do</h2>
|
||||
<p class="text-lg text-gray-600 text-center max-w-3xl mx-auto">AI Infinite empowers businesses to streamline document processing using advanced OCR and machine learning. Our tools automate data extraction from invoices, passports, and more—reducing manual work by up to 90%.</p>
|
||||
</div>
|
||||
|
||||
<!-- Our Vision -->
|
||||
<div data-aos="fade-up" data-aos-delay="100">
|
||||
<h2 class="text-4xl font-bold text-center mb-6">Our Vision</h2>
|
||||
<p class="text-lg text-gray-600 text-center max-w-3xl mx-auto">We envision a world where AI is as intuitive and accessible as the internet. Our mission is to embed AI seamlessly into workflows, making automation a natural extension of every business process.</p>
|
||||
</div>
|
||||
|
||||
<!-- Get in Touch Form -->
|
||||
<div data-aos="fade-up" data-aos-delay="200">
|
||||
<h2 class="text-4xl font-bold text-center mb-6">Get in Touch</h2>
|
||||
<p class="text-lg text-gray-600 text-center mb-6">Have questions? Reach out to our team today.</p>
|
||||
<form action="#submit" method="POST" class="max-w-2xl mx-auto space-y-4">
|
||||
<input type="email" name="email" placeholder="Your Work Email*" required class="w-full p-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500">
|
||||
<input type="tel" name="phone" placeholder="Contact Number" class="w-full p-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500">
|
||||
<textarea name="message" rows="4" placeholder="How Can We Help You?*" required class="w-full p-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500"></textarea>
|
||||
<button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white py-3 rounded-lg font-semibold transition">Send Message</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Request a Demo -->
|
||||
<div class="text-center" data-aos="fade-up" data-aos-delay="300">
|
||||
<h3 class="text-2xl font-bold mb-4">Talk to an AI Expert</h3>
|
||||
<p class="text-gray-600 mb-6 max-w-xl mx-auto">Book a free 15-minute call with our automation specialists to explore integrations, pricing, or see a live demo.</p>
|
||||
<a href="#demo" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-8 rounded-lg text-lg transition transform hover:scale-105">Request a Demo</a>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Footer -->
|
||||
<footer class="bg-gray-800 text-gray-200 py-10">
|
||||
<div class="container mx-auto px-6 text-center space-y-4">
|
||||
<img src="{{ url_for('static', filename='logos/aiinfinite.png') }}" class="h-10 mx-auto" alt="AI Infinite">
|
||||
<p>
|
||||
<a href="#api-docs" class="hover:underline mx-2">API</a> |
|
||||
<a href="#help" class="hover:underline mx-2">Help Center</a> |
|
||||
<a href="#blog" class="hover:underline mx-2">Blog</a> |
|
||||
<a href="#careers" class="hover:underline mx-2">Careers</a>
|
||||
</p>
|
||||
<p class="text-sm">+91 82753 67267 | connect@aiindia.ai | Pune, Maharashtra 411009</p>
|
||||
<div class="text-lg">
|
||||
<a href="https://twitter.com/AiIndia2?s=09" class="mx-2 hover:text-white"><i class="fab fa-twitter"></i></a>
|
||||
<a href="https://www.linkedin.com/company/ai-india/" class="mx-2 hover:text-white"><i class="fab fa-linkedin"></i></a>
|
||||
<a href="#" class="mx-2 hover:text-white"><i class="fab fa-medium"></i></a>
|
||||
</div>
|
||||
<p class="text-sm">© 2025 AI Infinite Technologies Inc.</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<!-- Scripts -->
|
||||
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
|
||||
<script>
|
||||
AOS.init({ duration: 800, once: true });
|
||||
document.getElementById('menu-btn').addEventListener('click', () => {
|
||||
document.getElementById('menu').classList.toggle('hidden');
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,178 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||
<title>Admin Dashboard – AI Infinite</title>
|
||||
<!-- Google Font -->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<!-- Bootstrap CSS -->
|
||||
<link
|
||||
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<!-- DataTables CSS -->
|
||||
<link
|
||||
href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<style>
|
||||
body {
|
||||
font-family: 'Roboto', sans-serif;
|
||||
background-color: #f0f2f5;
|
||||
padding: 2rem;
|
||||
}
|
||||
h2 {
|
||||
color: #007BFF;
|
||||
margin-bottom: 1.5rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
.dataTables_wrapper .dataTables_filter input {
|
||||
width: 250px;
|
||||
margin-left: 0.5rem;
|
||||
}
|
||||
.alert-fixed {
|
||||
position: fixed;
|
||||
top: 1rem;
|
||||
right: 1rem;
|
||||
z-index: 1050;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container-fluid">
|
||||
<h2>Admin Dashboard</h2>
|
||||
|
||||
<!-- Alert placeholder -->
|
||||
<div id="alert-area"></div>
|
||||
|
||||
<table
|
||||
id="users-table"
|
||||
class="table table-striped table-bordered align-middle"
|
||||
style="width:100%"
|
||||
>
|
||||
<thead class="table-primary">
|
||||
<tr>
|
||||
<th>Username</th>
|
||||
<th>Email</th>
|
||||
<th>Phone</th>
|
||||
<th>Invoices<br>Extracted</th>
|
||||
<th>API Key</th>
|
||||
<th>Account Limit</th>
|
||||
<th>Update</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for user in user_activity %}
|
||||
<tr>
|
||||
<td>{{ user.username }}</td>
|
||||
<td>{{ user.email }}</td>
|
||||
<td>{{ user.phone or '—' }}</td>
|
||||
<td>{{ user.invoices_extracted }}</td>
|
||||
<td>
|
||||
{% if user.api_keys %}
|
||||
<code>{{ user.api_keys[0].api_key }}</code>
|
||||
{% else %}
|
||||
<em>N/A</em>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
<input
|
||||
type="number"
|
||||
id="limit-{{ user.user_id }}"
|
||||
class="form-control form-control-sm text-center"
|
||||
value="{{ user.account_limit }}"
|
||||
min="1"
|
||||
/>
|
||||
</td>
|
||||
<td class="text-center">
|
||||
<button
|
||||
class="btn btn-sm btn-success"
|
||||
onclick="updateUserLimit('{{ user.user_id }}')"
|
||||
>
|
||||
Update
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<a href="{{ url_for('logout') }}" class="btn btn-danger mt-3">
|
||||
<i class="fas fa-sign-out-alt"></i> Logout
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- JS dependencies -->
|
||||
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
|
||||
<script
|
||||
src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"
|
||||
></script>
|
||||
<script
|
||||
src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"
|
||||
></script>
|
||||
<script
|
||||
src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"
|
||||
></script>
|
||||
|
||||
<script>
|
||||
// Initialize DataTable
|
||||
$(document).ready(function() {
|
||||
$('#users-table').DataTable({
|
||||
pageLength: 10,
|
||||
lengthChange: false,
|
||||
language: {
|
||||
search: "<strong>Filter:</strong>"
|
||||
},
|
||||
columnDefs: [
|
||||
{ orderable: false, targets: [2,5,6] } // disable sort on Phone, Limit, Update
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
// Show bootstrap alert
|
||||
function showAlert(type, message) {
|
||||
const html = `
|
||||
<div class="alert alert-${type} alert-dismissible fade show alert-fixed" role="alert">
|
||||
${message}
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
||||
</div>`;
|
||||
$('#alert-area').append(html);
|
||||
setTimeout(() => {
|
||||
$('.alert-fixed').alert('close');
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// AJAX update
|
||||
function updateUserLimit(userId) {
|
||||
const newLimit = $('#limit-' + userId).val();
|
||||
if (newLimit < 1) {
|
||||
showAlert('danger', 'Limit must be ≥ 1');
|
||||
return;
|
||||
}
|
||||
fetch('/admin/update-user-limit', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ user_id: userId, new_account_limit: newLimit })
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data.message) {
|
||||
showAlert('success', data.message);
|
||||
} else {
|
||||
showAlert('danger', data.error || 'Update failed');
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
console.error(err);
|
||||
showAlert('danger', 'Network error');
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,192 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Forgot Password - AIInfinite</title>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
|
||||
<style>
|
||||
:root {
|
||||
--white: #ffffff;
|
||||
--text-dark: #1a1a1a;
|
||||
--primary-color: #003087;
|
||||
--secondary-color: #666666;
|
||||
--background-light: #f0f2f5;
|
||||
--error-color: #d32f2f;
|
||||
--success-color: #155724;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Inter', sans-serif;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
color: var(--text-dark);
|
||||
background: var(--background-light);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.auth-form {
|
||||
background: var(--white);
|
||||
padding: 4rem;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
|
||||
width: 100%;
|
||||
max-width: 500px;
|
||||
margin: 2rem;
|
||||
animation: slideIn 0.5s ease-in-out;
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
from { transform: translateY(20px); opacity: 0; }
|
||||
to { transform: translateY(0); opacity: 1; }
|
||||
}
|
||||
|
||||
.form-title {
|
||||
font-size: 2.2rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.5rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.form-subtitle {
|
||||
color: var(--secondary-color);
|
||||
margin-bottom: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.auth-form-group {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.auth-form-group label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
font-weight: 600;
|
||||
color: var(--secondary-color);
|
||||
}
|
||||
|
||||
.auth-form-group input {
|
||||
width: 100%;
|
||||
padding: 1rem;
|
||||
border: 2px solid var(--background-light);
|
||||
border-radius: 8px;
|
||||
font-size: 1rem;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.auth-form-group input:focus {
|
||||
border-color: var(--primary-color);
|
||||
outline: none;
|
||||
box-shadow: 0 0 8px rgba(0, 48, 135, 0.2);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
width: 100%;
|
||||
padding: 1rem;
|
||||
background: var(--primary-color);
|
||||
color: var(--white);
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.3s ease;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background: #002366;
|
||||
}
|
||||
|
||||
.switch-auth {
|
||||
text-align: center;
|
||||
margin-top: 2rem;
|
||||
}
|
||||
|
||||
.btn-link {
|
||||
color: var(--primary-color);
|
||||
text-decoration: none;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.btn-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.security-note {
|
||||
color: var(--secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin-top: 1rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.flash-messages {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
.flash-message {
|
||||
padding: 1rem;
|
||||
margin: 1rem 0;
|
||||
border-radius: 8px;
|
||||
font-weight: 500;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.flash-message.success {
|
||||
background-color: #d4edda;
|
||||
color: var(--success-color);
|
||||
}
|
||||
|
||||
.flash-message.error {
|
||||
background-color: #f8d7da;
|
||||
color: var(--error-color);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.auth-form {
|
||||
padding: 2rem;
|
||||
margin: 1rem;
|
||||
}
|
||||
|
||||
.form-title {
|
||||
font-size: 1.8rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="auth-form">
|
||||
<h1 class="form-title">Reset Password</h1>
|
||||
<p class="form-subtitle">Enter your email to receive reset instructions</p>
|
||||
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
<ul class="flash-messages">
|
||||
{% for category, message in messages %}
|
||||
<li class="flash-message {{ category }}">{{ message }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
<form action="{{ url_for('forgot_password') }}" method="POST">
|
||||
<div class="auth-form-group">
|
||||
<label for="email">Email Address</label>
|
||||
<input type="email" id="email" name="email" required>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn-primary">Send Reset Link</button>
|
||||
|
||||
<div class="switch-auth">
|
||||
<p>Remember your password? <a href="{{ url_for('login') }}" class="btn-link">Sign In</a></p>
|
||||
<p class="security-note"><i class="fas fa-lock"></i> Secured with SSL Encryption</p>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,271 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Login to AIInfinite</title>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
|
||||
<style>
|
||||
:root {
|
||||
--white: #ffffff;
|
||||
--text-dark: #1a1a1a;
|
||||
--primary-color: #003087;
|
||||
--secondary-color: #666666;
|
||||
--background-light: #f0f2f5;
|
||||
--error-color: #d32f2f;
|
||||
--success-color: #155724;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Inter', sans-serif;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
color: var(--text-dark);
|
||||
background: var(--background-light);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.auth-form {
|
||||
background: var(--white);
|
||||
padding: 4rem;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
|
||||
width: 100%;
|
||||
max-width: 500px;
|
||||
margin: 2rem;
|
||||
animation: slideIn 0.5s ease-in-out;
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
from {
|
||||
transform: translateY(20px);
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
to {
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.form-title {
|
||||
font-size: 2.2rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.5rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.form-subtitle {
|
||||
color: var(--secondary-color);
|
||||
margin-bottom: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.auth-form-group {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.auth-form-group label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
font-weight: 600;
|
||||
color: var(--secondary-color);
|
||||
}
|
||||
|
||||
.auth-form-group input {
|
||||
width: 100%;
|
||||
padding: 1rem;
|
||||
border: 2px solid var(--background-light);
|
||||
border-radius: 8px;
|
||||
font-size: 1rem;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.auth-form-group input:focus {
|
||||
border-color: var(--primary-color);
|
||||
outline: none;
|
||||
box-shadow: 0 0 8px rgba(0, 48, 135, 0.2);
|
||||
}
|
||||
|
||||
.auth-form-checkbox {
|
||||
margin-bottom: 1.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
font-size: 0.95rem;
|
||||
color: var(--secondary-color);
|
||||
}
|
||||
|
||||
.auth-form-checkbox input {
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
width: 100%;
|
||||
padding: 1rem;
|
||||
background: var(--primary-color);
|
||||
color: var(--white);
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.3s ease;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background: #002366;
|
||||
}
|
||||
|
||||
.switch-auth {
|
||||
text-align: center;
|
||||
margin-top: 2rem;
|
||||
}
|
||||
|
||||
.btn-link {
|
||||
color: var(--primary-color);
|
||||
text-decoration: none;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.btn-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.security-note {
|
||||
color: var(--secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin-top: 1rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.flash-messages {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
.flash-message {
|
||||
padding: 1rem;
|
||||
margin: 1rem 0;
|
||||
border-radius: 8px;
|
||||
font-weight: 500;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.flash-message.success {
|
||||
background-color: #d4edda;
|
||||
color: var(--success-color);
|
||||
}
|
||||
|
||||
.flash-message.error {
|
||||
background-color: #f8d7da;
|
||||
color: var(--error-color);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.auth-form {
|
||||
padding: 2rem;
|
||||
margin: 1rem;
|
||||
}
|
||||
|
||||
.form-title {
|
||||
font-size: 1.8rem;
|
||||
}
|
||||
|
||||
/* ===== FORCE DMH BUTTON TOP RIGHT ===== */
|
||||
.btn-dmh-global {
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
/* 🔴 RIGHT SIDE */
|
||||
|
||||
padding: 10px 24px;
|
||||
background-color: #003087 !important;
|
||||
color: #ffffff !important;
|
||||
|
||||
border-radius: 6px;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
|
||||
text-decoration: none !important;
|
||||
z-index: 9999;
|
||||
}
|
||||
|
||||
.btn-dmh-global:hover {
|
||||
background-color: #002366 !important;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<a href="{{ url_for('login') }}" class="btn-dmh-global"
|
||||
style="position:fixed;top:20px;right:20px;background:blue;color:white;padding:10px;">
|
||||
DMH
|
||||
</a>
|
||||
|
||||
|
||||
|
||||
<div class="auth-form">
|
||||
<!-- <a href="{{ url_for('login') }}" class="btn-primary">
|
||||
DMH
|
||||
</a> -->
|
||||
|
||||
|
||||
<h1 class="form-title">Login to AI Infinite</h1>
|
||||
<p class="form-subtitle">Securely access your account</p>
|
||||
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
<ul class="flash-messages">
|
||||
{% for category, message in messages %}
|
||||
<li class="flash-message {{ category }}">{{ message }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
<form action="{{ url_for('login') }}" method="POST">
|
||||
<div class="auth-form-group">
|
||||
<label for="username">Username/Email</label>
|
||||
<input type="text" id="username" name="username" required>
|
||||
</div>
|
||||
|
||||
<div class="auth-form-group">
|
||||
<label for="password">Password</label>
|
||||
<input type="password" id="password" name="password" required>
|
||||
</div>
|
||||
|
||||
<!-- 👇 Remember Me Checkbox -->
|
||||
<div class="auth-form-checkbox">
|
||||
<input type="checkbox" id="remember" name="remember" value="yes">
|
||||
<label for="remember">Remember Me</label>
|
||||
</div>
|
||||
|
||||
<!-- <button type="submit" class="btn-primary">Sign In</button> -->
|
||||
<div class="login-actions">
|
||||
<button type="submit" class="btn-primary">
|
||||
Sign In
|
||||
</button>
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
<div class="switch-auth">
|
||||
<p>Don't have an account? <a href="{{ url_for('signup') }}" class="btn-link">Create Account</a></p>
|
||||
<p><a href="{{ url_for('forgot_password') }}" class="btn-link">Forgot Password?</a></p>
|
||||
<p class="security-note"><i class="fas fa-lock"></i> Secured with SSL Encryption</p>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,197 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Reset Password - AI Infinite</title>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
|
||||
<style>
|
||||
:root {
|
||||
--white: #ffffff;
|
||||
--text-dark: #1a1a1a;
|
||||
--primary-color: #003087;
|
||||
--secondary-color: #666666;
|
||||
--background-light: #f0f2f5;
|
||||
--error-color: #d32f2f;
|
||||
--success-color: #155724;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Inter', sans-serif;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
color: var(--text-dark);
|
||||
background: var(--background-light);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.auth-form {
|
||||
background: var(--white);
|
||||
padding: 4rem;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
|
||||
width: 100%;
|
||||
max-width: 500px;
|
||||
margin: 2rem;
|
||||
animation: slideIn 0.5s ease-in-out;
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
from { transform: translateY(20px); opacity: 0; }
|
||||
to { transform: translateY(0); opacity: 1; }
|
||||
}
|
||||
|
||||
.form-title {
|
||||
font-size: 2.2rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.5rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.form-subtitle {
|
||||
color: var(--secondary-color);
|
||||
margin-bottom: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.auth-form-group {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.auth-form-group label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
font-weight: 600;
|
||||
color: var(--secondary-color);
|
||||
}
|
||||
|
||||
.auth-form-group input {
|
||||
width: 100%;
|
||||
padding: 1rem;
|
||||
border: 2px solid var(--background-light);
|
||||
border-radius: 8px;
|
||||
font-size: 1rem;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.auth-form-group input:focus {
|
||||
border-color: var(--primary-color);
|
||||
outline: none;
|
||||
box-shadow: 0 0 8px rgba(0, 48, 135, 0.2);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
width: 100%;
|
||||
padding: 1rem;
|
||||
background: var(--primary-color);
|
||||
color: var(--white);
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.3s ease;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background: #002366;
|
||||
}
|
||||
|
||||
.switch-auth {
|
||||
text-align: center;
|
||||
margin-top: 2rem;
|
||||
}
|
||||
|
||||
.btn-link {
|
||||
color: var(--primary-color);
|
||||
text-decoration: none;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.btn-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.security-note {
|
||||
color: var(--secondary-color);
|
||||
font-size: 0.9rem;
|
||||
margin-top: 1rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.flash-messages {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
.flash-message {
|
||||
padding: 1rem;
|
||||
margin: 1rem 0;
|
||||
border-radius: 8px;
|
||||
font-weight: 500;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.flash-message.success {
|
||||
background-color: #d4edda;
|
||||
color: var(--success-color);
|
||||
}
|
||||
|
||||
.flash-message.error {
|
||||
background-color: #f8d7da;
|
||||
color: var(--error-color);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.auth-form {
|
||||
padding: 2rem;
|
||||
margin: 1rem;
|
||||
}
|
||||
|
||||
.form-title {
|
||||
font-size: 1.8rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="auth-form">
|
||||
<h1 class="form-title">Reset Password</h1>
|
||||
<p class="form-subtitle">Enter your new password</p>
|
||||
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
<ul class="flash-messages">
|
||||
{% for category, message in messages %}
|
||||
<li class="flash-message {{ category }}">{{ message }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
<form action="{{ url_for('reset_password') }}" method="POST">
|
||||
<div class="auth-form-group">
|
||||
<label for="password">New Password</label>
|
||||
<input type="password" id="password" name="password" required>
|
||||
</div>
|
||||
|
||||
<div class="auth-form-group">
|
||||
<label for="confirm_password">Confirm New Password</label>
|
||||
<input type="password" id="confirm_password" name="confirm_password" required>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn-primary">Reset Password</button>
|
||||
|
||||
<div class="switch-auth">
|
||||
<p>Back to <a href="{{ url_for('login') }}" class="btn-link">Login</a></p>
|
||||
<p class="security-note"><i class="fas fa-lock"></i> Secured with SSL Encryption</p>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,229 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||
<title>Sign Up – AI Infinite</title>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"
|
||||
/>
|
||||
<style>
|
||||
:root {
|
||||
--white: #ffffff;
|
||||
--text-dark: #1a1a1a;
|
||||
--primary: #003087;
|
||||
--primary-hover: #002366;
|
||||
--secondary: #666666;
|
||||
--bg-light: #f0f2f5;
|
||||
--error: #d32f2f;
|
||||
--success: #155724;
|
||||
--input-border: #ddd;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
font-family: 'Inter', sans-serif;
|
||||
margin: 0; padding: 0;
|
||||
color: var(--text-dark);
|
||||
background: var(--bg-light);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 1rem;
|
||||
}
|
||||
.auth-form {
|
||||
background: var(--white);
|
||||
padding: 3rem;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 8px 24px rgba(0,0,0,0.1);
|
||||
width: 100%;
|
||||
max-width: 480px;
|
||||
animation: slideIn 0.5s ease-out;
|
||||
}
|
||||
@keyframes slideIn {
|
||||
from { transform: translateY(20px); opacity: 0; }
|
||||
to { transform: translateY(0); opacity: 1; }
|
||||
}
|
||||
.form-title {
|
||||
font-size: 2rem;
|
||||
font-weight: 600;
|
||||
text-align: center;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
.form-sub {
|
||||
color: var(--secondary);
|
||||
text-align: center;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
.form-group {
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
.form-group label {
|
||||
display: block;
|
||||
font-weight: 500;
|
||||
margin-bottom: 0.5rem;
|
||||
color: var(--secondary);
|
||||
}
|
||||
.form-group input {
|
||||
width: 100%;
|
||||
padding: 0.85rem 1rem;
|
||||
border: 1.5px solid var(--input-border);
|
||||
border-radius: 8px;
|
||||
font-size: 1rem;
|
||||
transition: border-color 0.2s, box-shadow 0.2s;
|
||||
}
|
||||
.form-group input:focus {
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 0 6px rgba(0, 48, 135, 0.2);
|
||||
outline: none;
|
||||
}
|
||||
.form-group input:invalid {
|
||||
border-color: var(--error);
|
||||
}
|
||||
.btn-primary {
|
||||
width: 100%;
|
||||
padding: 0.9rem;
|
||||
background: var(--primary);
|
||||
color: var(--white);
|
||||
font-size: 1.05rem;
|
||||
font-weight: 600;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
.btn-primary:hover {
|
||||
background: var(--primary-hover);
|
||||
}
|
||||
.switch-auth {
|
||||
text-align: center;
|
||||
margin-top: 1.75rem;
|
||||
}
|
||||
.btn-link {
|
||||
color: var(--primary);
|
||||
text-decoration: none;
|
||||
font-weight: 600;
|
||||
}
|
||||
.btn-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.security-note {
|
||||
color: var(--secondary);
|
||||
font-size: 0.85rem;
|
||||
margin-top: 0.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.security-note i {
|
||||
margin-right: 0.4rem;
|
||||
}
|
||||
.flash-messages {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 1rem 0;
|
||||
}
|
||||
.flash-message {
|
||||
padding: 0.9rem 1rem;
|
||||
margin-bottom: 0.75rem;
|
||||
border-radius: 8px;
|
||||
font-weight: 500;
|
||||
text-align: center;
|
||||
}
|
||||
.flash-message.success {
|
||||
background: #d4edda;
|
||||
color: var(--success);
|
||||
}
|
||||
.flash-message.error {
|
||||
background: #f8d7da;
|
||||
color: var(--error);
|
||||
}
|
||||
@media (max-width: 500px) {
|
||||
.auth-form { padding: 2rem; }
|
||||
.form-title { font-size: 1.7rem; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="auth-form">
|
||||
<h1 class="form-title">Sign Up for AI Infinite</h1>
|
||||
<p class="form-sub">Create your account to get started</p>
|
||||
|
||||
{% with msgs = get_flashed_messages(with_categories=true) %}
|
||||
{% if msgs %}
|
||||
<ul class="flash-messages">
|
||||
{% for cat, msg in msgs %}
|
||||
<li class="flash-message {{ cat }}">{{ msg }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
<form action="{{ url_for('signup') }}" method="POST" novalidate>
|
||||
<div class="form-group">
|
||||
<label for="username">Username</label>
|
||||
<input
|
||||
type="text"
|
||||
id="username"
|
||||
name="username"
|
||||
required
|
||||
minlength="3"
|
||||
placeholder="Choose a username"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="email">Email address</label>
|
||||
<input
|
||||
type="email"
|
||||
id="email"
|
||||
name="email"
|
||||
required
|
||||
placeholder="you@example.com"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="phone">Phone number</label>
|
||||
<input
|
||||
type="tel"
|
||||
id="phone"
|
||||
name="phone"
|
||||
required
|
||||
pattern="^\+\d{1,3}\s?\d{4,14}$"
|
||||
placeholder="+91 98765 43210"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="password">Password</label>
|
||||
<input
|
||||
type="password"
|
||||
id="password"
|
||||
name="password"
|
||||
required
|
||||
minlength="6"
|
||||
placeholder="Create a secure password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn-primary">Sign Up</button>
|
||||
|
||||
<div class="switch-auth">
|
||||
<p>
|
||||
Already have an account?
|
||||
<a href="{{ url_for('login') }}" class="btn-link">Log In</a>
|
||||
</p>
|
||||
<p class="security-note">
|
||||
<i class="fas fa-lock"></i> Secured with SSL Encryption
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,396 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>User Dashboard - AI Infinite</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||
<style>
|
||||
/* Global Styles (unchanged) */
|
||||
:root {
|
||||
--primary-color: #007bff;
|
||||
--background-light: #f8f9fa;
|
||||
--text-dark: #333;
|
||||
--white: #fff;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
color: var(--text-dark);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
line-height: 1.6;
|
||||
background-color: var(--background-light);
|
||||
}
|
||||
|
||||
.navbar {
|
||||
background-color: #f7f7f7;
|
||||
padding: 1rem;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.navbar-brand {
|
||||
font-size: 1.5rem;
|
||||
font-weight: bold;
|
||||
color: var(--primary-color);
|
||||
text-decoration: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.navbar-toggler {
|
||||
padding: 0.25rem 0.5rem;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.navbar-toggler-icon {
|
||||
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba(0, 123, 255, 1)' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
|
||||
}
|
||||
|
||||
.main-container {
|
||||
display: flex;
|
||||
min-height: calc(100vh - 60px);
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
width: 250px;
|
||||
background-color: var(--white);
|
||||
border-right: 1px solid #dee2e6;
|
||||
padding: 1.5rem;
|
||||
position: fixed;
|
||||
height: 100%;
|
||||
z-index: 1000;
|
||||
transform: translateX(-100%);
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
.sidebar.active {
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
.sidebar .nav-link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
color: var(--text-dark);
|
||||
padding: 0.75rem 1rem;
|
||||
margin: 0.3rem 0;
|
||||
border-radius: 5px;
|
||||
text-decoration: none;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
|
||||
.sidebar .nav-link:hover {
|
||||
background-color: var(--background-light);
|
||||
}
|
||||
|
||||
.sidebar .nav-link.active {
|
||||
background-color: #e9ecef;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 800px;
|
||||
margin: 2rem auto;
|
||||
padding: 0 1rem;
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.card {
|
||||
background-color: var(--white);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
|
||||
padding: 1.5rem;
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: 1.5rem;
|
||||
margin-bottom: 1rem;
|
||||
color: var(--text-dark);
|
||||
}
|
||||
|
||||
.form-label {
|
||||
font-weight: 500;
|
||||
color: var(--text-dark);
|
||||
}
|
||||
|
||||
.form-control {
|
||||
border-radius: 5px;
|
||||
border: 1px solid #ccc;
|
||||
padding: 0.75rem;
|
||||
width: 100%;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background-color: var(--primary-color);
|
||||
color: var(--white);
|
||||
padding: 0.75rem 1.5rem;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
font-weight: bold;
|
||||
transition: background-color 0.3s;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background-color: #0056b3;
|
||||
}
|
||||
|
||||
.loading-container {
|
||||
display: none;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
border-radius: 50%;
|
||||
background-color: var(--primary-color);
|
||||
animation: bounce 1.5s infinite ease-in-out;
|
||||
}
|
||||
|
||||
.dot:nth-child(1) {
|
||||
animation-delay: 0s;
|
||||
}
|
||||
|
||||
.dot:nth-child(2) {
|
||||
animation-delay: 0.2s;
|
||||
}
|
||||
|
||||
.dot:nth-child(3) {
|
||||
animation-delay: 0.4s;
|
||||
}
|
||||
|
||||
@keyframes bounce {
|
||||
|
||||
0%,
|
||||
100% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
50% {
|
||||
transform: translateY(-10px);
|
||||
}
|
||||
}
|
||||
|
||||
.modal-body {
|
||||
padding: 1rem;
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.modal-body p {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background-color: #6c757d;
|
||||
color: var(--white);
|
||||
padding: 0.5rem 1rem;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background-color: #5a6268;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.sidebar {
|
||||
width: 220px;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 90%;
|
||||
margin: 1rem auto;
|
||||
}
|
||||
|
||||
.navbar {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.card {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
padding: 0.5rem 1rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<nav class="navbar">
|
||||
<div class="container-fluid">
|
||||
<button class="navbar-toggler" id="sidebarToggle"><span class="navbar-toggler-icon"></span></button>
|
||||
<a href="{{ url_for('index') }}" class="navbar-brand">
|
||||
<a src="{{ url_for('static', filename='logos/aiinfinite.png') }}" alt="AI Infinite Logo"
|
||||
style="height: 40px;">
|
||||
</a>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="main-container">
|
||||
<div class="sidebar">
|
||||
<div class="nav flex-column">
|
||||
<a class="nav-link" href="{{ url_for('home_logged_in') }}"><i class="fas fa-home"></i> Home
|
||||
</a>
|
||||
|
||||
<a class="nav-link active" href="{{ url_for('dashboard') }}"><i class="fas fa-tachometer-alt"></i>
|
||||
Dashboard Overview</a>
|
||||
<a href="{{ url_for('view_history') }}" class="nav-link"><i class="fas fa-history"></i> View Document
|
||||
History</a>
|
||||
<a href="javascript:void(0);" class="nav-link" id="generate-api-key-btn"><i class="fas fa-key"></i>
|
||||
Generate API Key</a>
|
||||
<a href="javascript:void(0);" class="nav-link" id="view-api-key-btn"><i class="fas fa-eye"></i> View API
|
||||
Key</a>
|
||||
<a class="nav-link" href="{{ url_for('logout') }}"><i class="fas fa-sign-out-alt"></i> Logout</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<!-- Flash Messages -->
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
{% for category, message in messages %}
|
||||
<div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
|
||||
<strong>{{ message }}</strong>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
<!-- Upload Document Card -->
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title">Upload Document</h5>
|
||||
<form id="upload-form" action="{{ url_for('upload_image') }}" method="POST"
|
||||
enctype="multipart/form-data">
|
||||
<div class="mb-3">
|
||||
<label for="doc_type" class="form-label">Select Document Type</label>
|
||||
<select class="form-control" id="doc_type" name="doc_type" required>
|
||||
<option value="invoice">Invoice</option>
|
||||
<option value="passport">Passport</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="file" class="form-label">Choose Document File (PDF or Image)</label>
|
||||
<input type="file" class="form-control" id="file" name="file"
|
||||
accept="image/*,application/pdf" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Upload and Extract</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="loading-container" id="loading-container">
|
||||
<div class="dot"></div>
|
||||
<div class="dot"></div>
|
||||
<div class="dot"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal for API Key Display -->
|
||||
<div class="modal fade" id="apiKeyModal" tabindex="-1" aria-labelledby="apiKeyModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="apiKeyModalLabel">Your API Key</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p>Your API Key: <span id="api-key-value"></span></p>
|
||||
<button class="btn btn-secondary" onclick="copyToClipboard()">Copy</button>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script>
|
||||
// Sidebar Toggle
|
||||
document.getElementById('sidebarToggle').addEventListener('click', function () {
|
||||
document.querySelector('.sidebar').classList.toggle('active');
|
||||
});
|
||||
|
||||
// Generate API Key
|
||||
document.getElementById('generate-api-key-btn').addEventListener('click', function () {
|
||||
fetch("{{ url_for('generate_api_key') }}", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "same-origin"
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
document.getElementById('api-key-value').innerText = data.api_key;
|
||||
new bootstrap.Modal(document.getElementById('apiKeyModal')).show();
|
||||
} else {
|
||||
alert('Error: ' + data.error);
|
||||
}
|
||||
})
|
||||
.catch(error => alert("An error occurred while generating the API key."));
|
||||
});
|
||||
|
||||
// View API Key
|
||||
document.getElementById('view-api-key-btn').addEventListener('click', function () {
|
||||
fetch("{{ url_for('get_api_key') }}", {
|
||||
method: "GET",
|
||||
credentials: "same-origin"
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
document.getElementById('api-key-value').innerText = data.api_key;
|
||||
new bootstrap.Modal(document.getElementById('apiKeyModal')).show();
|
||||
} else {
|
||||
alert('Error: ' + data.error);
|
||||
}
|
||||
})
|
||||
.catch(error => alert("An error occurred while fetching the API key."));
|
||||
});
|
||||
|
||||
// Copy to Clipboard
|
||||
function copyToClipboard() {
|
||||
const apiKey = document.getElementById('api-key-value').innerText;
|
||||
navigator.clipboard.writeText(apiKey).then(() => {
|
||||
alert('API Key copied to clipboard');
|
||||
}, () => {
|
||||
alert('Failed to copy API Key');
|
||||
});
|
||||
}
|
||||
|
||||
// Loading Animation
|
||||
document.getElementById('upload-form').addEventListener('submit', function () {
|
||||
document.getElementById('loading-container').style.display = 'flex';
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,425 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>User Dashboard - AI Infinite</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||
<style>
|
||||
/* Global Styles (unchanged) */
|
||||
:root {
|
||||
--primary-color: #007bff;
|
||||
--background-light: #f8f9fa;
|
||||
--text-dark: #333;
|
||||
--white: #fff;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
color: var(--text-dark);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
line-height: 1.6;
|
||||
background-color: var(--background-light);
|
||||
}
|
||||
|
||||
.navbar {
|
||||
background-color: #f7f7f7;
|
||||
padding: 1rem;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.navbar-brand {
|
||||
font-size: 1.5rem;
|
||||
font-weight: bold;
|
||||
color: var(--primary-color);
|
||||
text-decoration: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.navbar-toggler {
|
||||
padding: 0.25rem 0.5rem;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.navbar-toggler-icon {
|
||||
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba(0, 123, 255, 1)' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
|
||||
}
|
||||
|
||||
.main-container {
|
||||
display: flex;
|
||||
min-height: calc(100vh - 60px);
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
width: 250px;
|
||||
background-color: var(--white);
|
||||
border-right: 1px solid #dee2e6;
|
||||
padding: 1.5rem;
|
||||
position: fixed;
|
||||
height: 100%;
|
||||
z-index: 1000;
|
||||
transform: translateX(-100%);
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
.sidebar.active {
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
.sidebar .nav-link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
color: var(--text-dark);
|
||||
padding: 0.75rem 1rem;
|
||||
margin: 0.3rem 0;
|
||||
border-radius: 5px;
|
||||
text-decoration: none;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
|
||||
.sidebar .nav-link:hover {
|
||||
background-color: var(--background-light);
|
||||
}
|
||||
|
||||
.sidebar .nav-link.active {
|
||||
background-color: #e9ecef;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 800px;
|
||||
margin: 2rem auto;
|
||||
padding: 0 1rem;
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.card {
|
||||
background-color: var(--white);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
|
||||
padding: 1.5rem;
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: 1.5rem;
|
||||
margin-bottom: 1rem;
|
||||
color: var(--text-dark);
|
||||
}
|
||||
|
||||
.form-label {
|
||||
font-weight: 500;
|
||||
color: var(--text-dark);
|
||||
}
|
||||
|
||||
.form-control {
|
||||
border-radius: 5px;
|
||||
border: 1px solid #ccc;
|
||||
padding: 0.75rem;
|
||||
width: 100%;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background-color: var(--primary-color);
|
||||
color: var(--white);
|
||||
padding: 0.75rem 1.5rem;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
font-weight: bold;
|
||||
transition: background-color 0.3s;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background-color: #0056b3;
|
||||
}
|
||||
|
||||
.loading-container {
|
||||
display: none;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
border-radius: 50%;
|
||||
background-color: var(--primary-color);
|
||||
animation: bounce 1.5s infinite ease-in-out;
|
||||
}
|
||||
|
||||
.dot:nth-child(1) {
|
||||
animation-delay: 0s;
|
||||
}
|
||||
|
||||
.dot:nth-child(2) {
|
||||
animation-delay: 0.2s;
|
||||
}
|
||||
|
||||
.dot:nth-child(3) {
|
||||
animation-delay: 0.4s;
|
||||
}
|
||||
|
||||
@keyframes bounce {
|
||||
|
||||
0%,
|
||||
100% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
50% {
|
||||
transform: translateY(-10px);
|
||||
}
|
||||
}
|
||||
|
||||
.modal-body {
|
||||
padding: 1rem;
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.modal-body p {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background-color: #6c757d;
|
||||
color: var(--white);
|
||||
padding: 0.5rem 1rem;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background-color: #5a6268;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.sidebar {
|
||||
width: 220px;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 90%;
|
||||
margin: 1rem auto;
|
||||
}
|
||||
|
||||
.navbar {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.card {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
padding: 0.5rem 1rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<nav class="navbar navbar-light bg-white shadow-sm">
|
||||
<div class="container-fluid d-flex align-items-center justify-content-center position-relative">
|
||||
|
||||
<!-- Sidebar Toggle (Left) -->
|
||||
<button class="navbar-toggler position-absolute start-0 ms-3" id="sidebarToggle">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
|
||||
<!-- Center Logo -->
|
||||
<a href="{{ url_for('index') }}" class="navbar-brand m-0">
|
||||
<img src="{{ url_for('static', filename='logos/logo.png') }}" alt="AI Infinite Logo"
|
||||
class="navbar-logo">
|
||||
</a>
|
||||
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
|
||||
<div class="main-container">
|
||||
<div class="sidebar">
|
||||
<div class="nav flex-column">
|
||||
<a class="nav-link" href="{{ url_for('home_logged_in') }}"><i class="fas fa-home"></i> Home
|
||||
</a>
|
||||
|
||||
<a class="nav-link active" href="{{ url_for('dmh_dashboard') }}"><i class="fas fa-tachometer-alt"></i>
|
||||
Dashboard Overview</a>
|
||||
<a href="{{ url_for('view_history') }}" class="nav-link"><i class="fas fa-history"></i> View Document
|
||||
History</a>
|
||||
<a href="javascript:void(0);" class="nav-link" id="generate-api-key-btn"><i class="fas fa-key"></i>
|
||||
Generate API Key</a>
|
||||
<a href="javascript:void(0);" class="nav-link" id="view-api-key-btn"><i class="fas fa-eye"></i> View API
|
||||
Key</a>
|
||||
<a class="nav-link" href="{{ url_for('logout') }}"><i class="fas fa-sign-out-alt"></i> Logout</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<!-- Flash Messages -->
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
{% for category, message in messages %}
|
||||
<div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
|
||||
<strong>{{ message }}</strong>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
<!-- Upload Document Card -->
|
||||
<div class="container mt-5">
|
||||
<div class="row justify-content-center">
|
||||
<div class="col-md-12">
|
||||
|
||||
<div class="card shadow">
|
||||
<div class="card-body">
|
||||
|
||||
<h4 class="card-title text-center mb-4">
|
||||
Upload Invoice
|
||||
</h4>
|
||||
|
||||
<form id="upload-form" action="{{ url_for('upload_image') }}" method="POST"
|
||||
enctype="multipart/form-data">
|
||||
|
||||
|
||||
<!-- hidden document type -->
|
||||
<input type="hidden" name="doc_type" value="invoice">
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="file" class="form-label">
|
||||
Choose Invoice File (PDF or Image)
|
||||
</label>
|
||||
<input type="file" class="form-control" id="file" name="file"
|
||||
accept="image/*,application/pdf" required>
|
||||
</div>
|
||||
|
||||
<div class="d-grid">
|
||||
<button type="submit" class="btn btn-primary btn-lg">
|
||||
Upload and Extract
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="text-center mt-3" id="loading-container" style="display:none;">
|
||||
<div class="spinner-border text-primary" role="status">
|
||||
<span class="visually-hidden">Loading...</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- Modal for API Key Display -->
|
||||
<div class="modal fade" id="apiKeyModal" tabindex="-1" aria-labelledby="apiKeyModalLabel"
|
||||
aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="apiKeyModalLabel">Your API Key</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p>Your API Key: <span id="api-key-value"></span></p>
|
||||
<button class="btn btn-secondary" onclick="copyToClipboard()">Copy</button>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script>
|
||||
// Sidebar Toggle
|
||||
document.getElementById('sidebarToggle').addEventListener('click', function () {
|
||||
document.querySelector('.sidebar').classList.toggle('active');
|
||||
});
|
||||
|
||||
// Generate API Key
|
||||
document.getElementById('generate-api-key-btn').addEventListener('click', function () {
|
||||
fetch("{{ url_for('generate_api_key') }}", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "same-origin"
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
document.getElementById('api-key-value').innerText = data.api_key;
|
||||
new bootstrap.Modal(document.getElementById('apiKeyModal')).show();
|
||||
} else {
|
||||
alert('Error: ' + data.error);
|
||||
}
|
||||
})
|
||||
.catch(error => alert("An error occurred while generating the API key."));
|
||||
});
|
||||
|
||||
// View API Key
|
||||
document.getElementById('view-api-key-btn').addEventListener('click', function () {
|
||||
fetch("{{ url_for('get_api_key') }}", {
|
||||
method: "GET",
|
||||
credentials: "same-origin"
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
document.getElementById('api-key-value').innerText = data.api_key;
|
||||
new bootstrap.Modal(document.getElementById('apiKeyModal')).show();
|
||||
} else {
|
||||
alert('Error: ' + data.error);
|
||||
}
|
||||
})
|
||||
.catch(error => alert("An error occurred while fetching the API key."));
|
||||
});
|
||||
|
||||
// Copy to Clipboard
|
||||
function copyToClipboard() {
|
||||
const apiKey = document.getElementById('api-key-value').innerText;
|
||||
navigator.clipboard.writeText(apiKey).then(() => {
|
||||
alert('API Key copied to clipboard');
|
||||
}, () => {
|
||||
alert('Failed to copy API Key');
|
||||
});
|
||||
}
|
||||
|
||||
// Loading Animation
|
||||
document.getElementById("upload-form").addEventListener("submit", function () {
|
||||
document.getElementById("loading-container").style.display = "block";
|
||||
});
|
||||
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,534 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="description" content="AI Infinite: Automate data extraction from PDFs, invoices, passports, and more with our AI-powered parser. Save time, boost productivity, and integrate seamlessly with your tools." />
|
||||
<meta name="keywords" content="AI document parser, data extraction, PDF parser, invoice extraction, passport extraction, OCR, AI Infinite, automation" />
|
||||
<title>AI Infinite - Revolutionize Your Workflow with AI-Powered Data Extraction</title>
|
||||
<!-- Tailwind CSS CDN -->
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<!-- Font Awesome for icons -->
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||
<!-- AOS CSS -->
|
||||
<link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
|
||||
|
||||
<link rel="icon" href="{{ url_for('static', filename='logos/ai infinite.jpg') }}" type="image/x-icon">
|
||||
|
||||
</head>
|
||||
<body class="antialiased text-gray-800">
|
||||
!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="description" content="AI Infinite: Automate data extraction from PDFs, invoices, passports, and more with our AI-powered parser. Save time, boost productivity, and integrate seamlessly with your tools." />
|
||||
<meta name="keywords" content="AI document parser, data extraction, PDF parser, invoice extraction, passport extraction, OCR, AI Infinite, automation" />
|
||||
<title>AI Infinite - Revolutionize Your Workflow with AI-Powered Data Extraction</title>
|
||||
<!-- Tailwind CSS CDN -->
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<!-- Font Awesome for icons -->
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||
<!-- AOS CSS -->
|
||||
<link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
|
||||
|
||||
<link rel="icon" href="{{ url_for('static', filename='logos/ai infinite.jpg') }}" type="image/x-icon">
|
||||
|
||||
</head>
|
||||
<body class="antialiased text-gray-800">
|
||||
|
||||
<!-- Updated Navbar -->
|
||||
<nav id="navbar" class="fixed top-0 left-0 w-full bg-[#f7f7f7] backdrop-blur shadow-md z-50">
|
||||
<div class="container mx-auto px-6 py-4 flex items-center">
|
||||
<!-- Logo / Brand -->
|
||||
<a href="{{ url_for('home_logged_in') if logged_in else url_for('index') }}"
|
||||
class="flex items-center space-x-2 hover:opacity-90">
|
||||
<img src="{{ url_for('static', filename='logos/aiinfinite.png') }}"
|
||||
alt="AI Infinite Logo"
|
||||
class="h-12 md:h-16 w-auto" />
|
||||
</a>
|
||||
|
||||
<!-- Combined Right-side Links -->
|
||||
<div class="hidden md:flex items-center ml-auto space-x-12">
|
||||
<a href="{{ url_for('invoice', doc_type='invoice') }}" class="text-gray-700 hover:text-blue-600 font-medium">Invoice</a>
|
||||
<a href="{{ url_for('passport', doc_type='passport') }}" class="text-gray-700 hover:text-blue-600 font-medium">Passport</a>
|
||||
<a href="{{ url_for('pricing') }}" class="text-gray-700 hover:text-blue-600 font-medium">Pricing</a>
|
||||
<a href="{{ url_for('about') }}" class="text-gray-700 hover:text-blue-600 font-medium">About</a>
|
||||
{% if logged_in %}
|
||||
<a href="{{ url_for('dashboard') }}" class="text-gray-700 hover:text-blue-600 font-medium">Dashboard</a>
|
||||
<a href="{{ url_for('logout') }}" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg font-semibold">Logout</a>
|
||||
{% else %}
|
||||
<a href="{{ url_for('login') }}" class="text-gray-700 hover:text-blue-600 font-medium">Log in</a>
|
||||
<a href="{{ url_for('login') }}" class="bg-blue-600 hover:bg-blue-700 text-white px-5 py-2 rounded-lg font-semibold">Get Started</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- Mobile Menu Button -->
|
||||
<button id="menu-btn" class="md:hidden text-gray-700 focus:outline-none">
|
||||
<i class="fas fa-bars fa-2x"></i>
|
||||
</button>
|
||||
</div>
|
||||
<!-- Mobile Menu Content -->
|
||||
<div id="menu" class="hidden md:hidden bg-[#f7f7f7] backdrop-blur shadow-inner">
|
||||
<div class="flex flex-col space-y-2 px-6 py-4">
|
||||
<a href="{{ url_for('invoice', doc_type='invoice') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Invoice</a>
|
||||
<a href="{{ url_for('passport', doc_type='passport') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Passport</a>
|
||||
<a href="{{ url_for('pricing') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Pricing</a>
|
||||
<a href="{{ url_for('about') }}" class="block text-gray-700 hover:text-blue-600 font-medium">About</a>
|
||||
{% if logged_in %}
|
||||
<a href="{{ url_for('dashboard') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Dashboard</a>
|
||||
<a href="{{ url_for('logout') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Logout</a>
|
||||
{% else %}
|
||||
<a href="{{ url_for('login') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Log in</a>
|
||||
<a href="{{ url_for('login') }}" class="block bg-blue-600 hover:bg-blue-700 text-white px-5 py-2 rounded-lg font-semibold text-center">Get Started</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
|
||||
<!-- Hero Section -->
|
||||
<section class="relative h-[80vh] flex items-center justify-center text-center text-white pt-20"
|
||||
style='background-image: url("https://images.unsplash.com/photo-1519389950473-47ba0277781c?ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80");
|
||||
background-size: cover;
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;'>
|
||||
<div class="absolute inset-0 bg-black opacity-50"></div>
|
||||
<div class="relative container mx-auto px-4 z-10">
|
||||
<h1 class="text-4xl sm:text-5xl font-bold mb-4" data-aos="fade-up">AI-Powered Data Extraction</h1>
|
||||
<p class="text-lg sm:text-2xl mb-8" data-aos="fade-up" data-aos-delay="100">Unlock actionable insights from your documents with cutting-edge AI. Streamline processes, reduce manual tasks, and drive efficiency like never before with AI Infinite.</p>
|
||||
<a href="{{ url_for('login') }}" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-8 rounded text-xl transform hover:scale-105 transition duration-300" data-aos="fade-up" data-aos-delay="200">Get Started</a>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- How It Works Section -->
|
||||
<section class="py-16 bg-gray-50">
|
||||
<div class="container mx-auto px-4">
|
||||
<h2 class="text-3xl font-bold text-center mb-12" data-aos="fade-up">How It Works</h2>
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-12">
|
||||
<!-- Step 1 -->
|
||||
<div class="flex flex-col items-center text-center" data-aos="fade-up" data-aos-delay="0">
|
||||
<div class="p-6 bg-white rounded-full shadow-lg mb-4">
|
||||
<i class="fas fa-upload text-blue-600 text-4xl animate-bounce"></i>
|
||||
</div>
|
||||
<h3 class="text-xl font-semibold mb-2">1. Upload</h3>
|
||||
<p>Drag & drop your documents or choose files from your device. We support PNG, JPG, PDF, and more.</p>
|
||||
</div>
|
||||
<!-- Step 2 -->
|
||||
<div class="flex flex-col items-center text-center" data-aos="fade-up" data-aos-delay="200">
|
||||
<div class="p-6 bg-white rounded-full shadow-lg mb-4">
|
||||
<i class="fas fa-microchip text-blue-600 text-4xl animate-bounce"></i>
|
||||
</div>
|
||||
<h3 class="text-xl font-semibold mb-2">2. Detect</h3>
|
||||
<p>Our AI scans the document to identify key fields like names, dates, totals, IDs, and other important details.</p>
|
||||
</div>
|
||||
<!-- Step 3 -->
|
||||
<div class="flex flex-col items-center text-center" data-aos="fade-up" data-aos-delay="400">
|
||||
<div class="p-6 bg-white rounded-full shadow-lg mb-4">
|
||||
<i class="fas fa-file-export text-blue-600 text-4xl animate-bounce"></i>
|
||||
</div>
|
||||
<h3 class="text-xl font-semibold mb-2">3. Extract</h3>
|
||||
<p>Receive clean, structured data in JSON or Excel format—perfect for automation, integration, and analytics.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-center mt-8 text-sm text-gray-600">
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Core Features Section -->
|
||||
<section id="features" class="py-16 bg-white">
|
||||
<div class="container mx-auto px-4">
|
||||
<h2 class="text-3xl font-bold text-center mb-12" data-aos="fade-up">Core Features</h2>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-8">
|
||||
<!-- Feature 1 -->
|
||||
<div class="p-8 bg-gray-50 rounded-lg shadow hover:shadow-lg transform hover:scale-105 transition duration-300" data-aos="fade-up" data-aos-delay="100">
|
||||
<div class="text-blue-600 mb-4 text-center">
|
||||
<i class="fas fa-file-alt fa-3x"></i>
|
||||
</div>
|
||||
<h3 class="text-xl font-semibold text-center mb-2">Multi-format Support</h3>
|
||||
<p class="text-center text-gray-600">Extract data from PDFs, scanned images, and camera‑captured documents easily.</p>
|
||||
</div>
|
||||
<!-- Feature 2 -->
|
||||
<div class="p-8 bg-gray-50 rounded-lg shadow hover:shadow-lg transform hover:scale-105 transition duration-300" data-aos="fade-up" data-aos-delay="200">
|
||||
<div class="text-blue-600 mb-4 text-center">
|
||||
<i class="fas fa-table fa-3x"></i>
|
||||
</div>
|
||||
<h3 class="text-xl font-semibold text-center mb-2">Export to Excel/JSON</h3>
|
||||
<p class="text-center text-gray-600">Download your output in Excel or machine‑readable JSON format—ready for integration.</p>
|
||||
</div>
|
||||
<!-- Feature 3 -->
|
||||
<div class="p-8 bg-gray-50 rounded-lg shadow hover:shadow-lg transform hover:scale-105 transition duration-300" data-aos="fade-up" data-aos-delay="300">
|
||||
<div class="text-blue-600 mb-4 text-center">
|
||||
<i class="fas fa-lock fa-3x"></i>
|
||||
</div>
|
||||
<h3 class="text-xl font-semibold text-center mb-2">Enterprise‑grade Security</h3>
|
||||
<p class="text-center text-gray-600">End‑to‑end encryption and secure data handling ensure your privacy and safety.</p>
|
||||
</div>
|
||||
<!-- Feature 4 (Updated) -->
|
||||
<div class="p-8 bg-gray-50 rounded-lg shadow hover:shadow-lg transform hover:scale-105 transition duration-300" data-aos="fade-up" data-aos-delay="400">
|
||||
<div class="text-blue-600 mb-4 text-center">
|
||||
<i class="fas fa-robot fa-3x"></i>
|
||||
</div>
|
||||
<h3 class="text-xl font-semibold text-center mb-2">Trained AI Models</h3>
|
||||
<p class="text-center text-gray-600">Leverages AI models trained on diverse invoice data for superior accuracy.</p>
|
||||
</div>
|
||||
<!-- Feature 5 -->
|
||||
<div class="p-8 bg-gray-50 rounded-lg shadow hover:shadow-lg transform hover:scale-105 transition duration-300" data-aos="fade-up" data-aos-delay="500">
|
||||
<div class="text-blue-600 mb-4 text-center">
|
||||
<i class="fas fa-plug fa-3x"></i>
|
||||
</div>
|
||||
<h3 class="text-xl font-semibold text-center mb-2">API & Dashboard Access</h3>
|
||||
<p class="text-center text-gray-600">Seamlessly integrate with our APIs or manage your documents through a user‑friendly dashboard.</p>
|
||||
</div>
|
||||
<!-- Feature 6 -->
|
||||
<div class="p-8 bg-gray-50 rounded-lg shadow hover:shadow-lg transform hover:scale-105 transition duration-300" data-aos="fade-up" data-aos-delay="600">
|
||||
<div class="text-blue-600 mb-4 text-center">
|
||||
<i class="fas fa-cogs fa-3x"></i>
|
||||
</div>
|
||||
<h3 class="text-xl font-semibold text-center mb-2">Custom Fields</h3>
|
||||
<p class="text-center text-gray-600">Define and extract any fields unique to your workflows.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
|
||||
|
||||
<!-- Who It's For Section -->
|
||||
<section class="py-16 bg-gray-50">
|
||||
<div class="container mx-auto px-4">
|
||||
<h2 class="text-3xl font-bold text-center mb-12" data-aos="fade-up">Who It's For</h2>
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-8">
|
||||
<div class="p-6 bg-white rounded-lg shadow" data-aos="fade-up">
|
||||
<h3 class="text-xl font-semibold mb-3">Businesses & Enterprises</h3>
|
||||
<p class="text-gray-600">Automate invoice processing, compliance tracking, or identity validation to save time and reduce errors.</p>
|
||||
</div>
|
||||
<div class="p-6 bg-white rounded-lg shadow" data-aos="fade-up">
|
||||
<h3 class="text-xl font-semibold mb-3">Developers & Startups</h3>
|
||||
<p class="text-gray-600">Integrate our robust APIs into your applications and streamline your workflows with ease.</p>
|
||||
</div>
|
||||
<div class="p-6 bg-white rounded-lg shadow" data-aos="fade-up">
|
||||
<h3 class="text-xl font-semibold mb-3">Government & Institutions</h3>
|
||||
<p class="text-gray-600">Digitize records, IDs, and multi-language documents securely while optimizing workflow efficiency.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Contact Form Section -->
|
||||
<div class="container mx-auto max-w-4xl px-4 py-8 bg-white rounded-lg shadow-[0_10px_25px_rgba(0,0,0,0.5)] relative flex flex-col md:flex-row justify-between items-start" data-aos="fade-up" style="margin-bottom: -200px;">
|
||||
<div class="w-full md:w-1/2 p-4 z-10 relative">
|
||||
<h2 class="text-2xl font-bold text-blue-900 mb-4">Have more questions?</h2>
|
||||
<p class="text-gray-500 text-sm mb-4">GET IN TOUCH</p>
|
||||
<form id="query-form" action="/submit" method="post" class="space-y-4">
|
||||
<div>
|
||||
<label for="work-email" class="block text-sm font-medium text-gray-700">Your work email*</label>
|
||||
<input type="email" id="work-email" name="email" class="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500" required>
|
||||
</div>
|
||||
<div>
|
||||
<label for="contact-number" class="block text-sm font-medium text-gray-700">Contact number</label>
|
||||
<input type="tel" id="contact-number" name="contact" class="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500">
|
||||
</div>
|
||||
<div>
|
||||
<label for="help-message" class="block text-sm font-medium text-gray-700">How can we help you?*</label>
|
||||
<textarea id="help-message" name="message" class="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 h-24 resize-y" required></textarea>
|
||||
</div>
|
||||
<button type="submit" class="w-full md:w-auto bg-blue-900 text-white px-4 py-2 rounded-md hover:bg-blue-800 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
|
||||
Submit Query >>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
<div class="w-full md:w-1/2 p-4 border-l border-gray-300 md:border-l-2 z-10 relative">
|
||||
<h3 class="text-xl font-semibold text-blue-900 mb-2">Talk to an AI expert</h3>
|
||||
<p class="text-gray-600 mb-4">Get a free 15-minute consultation with our Automation experts. We can discuss Pricing, Integrations or try the app live on your documents.</p>
|
||||
<!-- Button to trigger the popup modal -->
|
||||
<button id="demo-btn" class="bg-blue-900 text-white px-4 py-2 rounded-md hover:bg-blue-800 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 flex items-center">
|
||||
Request a Demo
|
||||
<span class="ml-2"><i class="fas fa-user"></i><i class="fas fa-user ml-1"></i></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<footer class="bg-gray-800 text-gray-200 pt-64 pb-8">
|
||||
<div class="container mx-auto px-4 text-center">
|
||||
<p class="mb-2">© 2025 AI Infinite. All rights reserved.</p>
|
||||
<p class="mb-2">
|
||||
<a href="#" class="hover:underline mx-2">Features</a>|
|
||||
<a href="#" class="hover:underline mx-2">Integrations</a>|
|
||||
<a href="#" class="hover:underline mx-2">Pricing</a>|
|
||||
<a href="#" class="hover:underline mx-2">Blog</a>|
|
||||
<a href="#" class="hover:underline mx-2">Help Center</a>|
|
||||
<a href="#" class="hover:underline mx-2">API</a>
|
||||
</p>
|
||||
<p class="mb-2">
|
||||
<a href="#" class="hover:underline mx-2">Terms</a>|
|
||||
<a href="#" class="hover:underline mx-2">Privacy Policy</a>|
|
||||
<a href="#" class="hover:underline mx-2">Security</a>|
|
||||
<a href="#" class="hover:underline mx-2">GDPR</a>
|
||||
</p>
|
||||
<p>
|
||||
Follow us:
|
||||
<a href="#" class="mx-2 transform hover:scale-125 transition duration-300"><i class="fab fa-twitter"></i></a>
|
||||
<a href="#" class="mx-2 transform hover:scale-125 transition duration-300"><i class="fab fa-linkedin"></i></a>
|
||||
<a href="#" class="mx-2 transform hover:scale-125 transition duration-300"><i class="fab fa-facebook"></i></a>
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
Popup Modal
|
||||
<div id="demo-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden flex items-center justify-center z-50">
|
||||
<!-- Increase max-w so we can see two columns side by side -->
|
||||
<div class="bg-white p-6 rounded-lg shadow-lg w-full max-w-3xl mx-4 relative">
|
||||
<button
|
||||
id="close-modal"
|
||||
class="absolute top-2 right-2 text-gray-500 hover:text-gray-700"
|
||||
>
|
||||
<i class="fas fa-times"></i>
|
||||
</button>
|
||||
|
||||
<!-- Two columns inside the modal -->
|
||||
<div class="flex flex-col md:flex-row md:gap-6">
|
||||
<!-- Left column: Demo info and bullet points -->
|
||||
<div class="md:w-1/2 space-y-4 mb-4 md:mb-0">
|
||||
<h2 class="text-2xl font-bold text-blue-900">Demo Call</h2>
|
||||
<p class="text-gray-600">
|
||||
Find out why 10,000+ customers trust Nanonets!
|
||||
</p>
|
||||
<p class="text-gray-600">
|
||||
In this demo we'll show you how we:
|
||||
</p>
|
||||
<ul class="list-disc list-inside text-gray-600 mb-4">
|
||||
<li>Achieve 97% accuracy with our best in class Intelligent Document Processing platform 📄</li>
|
||||
<li>10x your productivity with our seamless workflows and automation engines ⚙️</li>
|
||||
<li>Scale to your needs while achieving a meaningful ROI 💡</li>
|
||||
</ul>
|
||||
<p class="text-gray-600">
|
||||
Interested? Click Schedule Event to find available time slots.
|
||||
</p>
|
||||
<p class="text-gray-600">Looking forward to seeing you!</p>
|
||||
</div>
|
||||
|
||||
<!-- Right column: Form -->
|
||||
<div class="md:w-1/2 space-y-4">
|
||||
<form id="demo-form" action="/schedule" method="post" class="space-y-4">
|
||||
<div>
|
||||
<label for="name" class="block text-sm font-medium text-gray-700">Name *</label>
|
||||
<input
|
||||
type="text"
|
||||
id="name"
|
||||
name="name"
|
||||
class="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
|
||||
required
|
||||
>
|
||||
</div>
|
||||
<div>
|
||||
<label for="company-email" class="block text-sm font-medium text-gray-700">Company email *</label>
|
||||
<input
|
||||
type="email"
|
||||
id="company-email"
|
||||
name="company-email"
|
||||
class="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
|
||||
required
|
||||
>
|
||||
</div>
|
||||
<div>
|
||||
<label for="timezone" class="block text-sm font-medium text-gray-700">
|
||||
Which time zone works best for the meeting? *
|
||||
</label>
|
||||
<div class="mt-1 space-y-2">
|
||||
<label class="flex items-center">
|
||||
<input type="radio" name="timezone" value="americas" class="form-radio text-blue-500" required>
|
||||
<span class="ml-2 text-gray-700">Americas</span>
|
||||
</label>
|
||||
<label class="flex items-center">
|
||||
<input type="radio" name="timezone" value="europe" class="form-radio text-blue-500">
|
||||
<span class="ml-2 text-gray-700">Europe</span>
|
||||
</label>
|
||||
<label class="flex items-center">
|
||||
<input type="radio" name="timezone" value="asia-pacific" class="form-radio text-blue-500">
|
||||
<span class="ml-2 text-gray-700">Asia Pacific & Australia</span>
|
||||
</label>
|
||||
<label class="flex items-center">
|
||||
<input type="radio" name="timezone" value="middle-east" class="form-radio text-blue-500">
|
||||
<span class="ml-2 text-gray-700">Middle East</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<!-- "Schedule Event" button is visible here -->
|
||||
<button
|
||||
type="submit"
|
||||
class="w-full bg-blue-900 text-white px-4 py-2 rounded-md hover:bg-blue-800 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
|
||||
>
|
||||
Schedule Event
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- JavaScript for Popup -->
|
||||
<script>
|
||||
// Show modal when "Request a Demo" button is clicked
|
||||
document.getElementById('demo-btn').addEventListener('click', function() {
|
||||
document.getElementById('demo-modal').classList.remove('hidden');
|
||||
});
|
||||
|
||||
// Hide modal when the close (X) button is clicked
|
||||
document.getElementById('close-modal').addEventListener('click', function() {
|
||||
document.getElementById('demo-modal').classList.add('hidden');
|
||||
});
|
||||
|
||||
// Hide modal if user clicks outside the modal content
|
||||
document.getElementById('demo-modal').addEventListener('click', function(e) {
|
||||
if (e.target === this) {
|
||||
this.classList.add('hidden');
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- Thank You Popup Modal -->
|
||||
<div id="thank-you-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden flex items-center justify-center z-50">
|
||||
<div class="bg-white p-6 rounded-lg shadow-lg w-full max-w-sm mx-4 relative text-center">
|
||||
<button id="close-thankyou" class="absolute top-2 right-2 text-gray-500 hover:text-gray-700">
|
||||
<i class="fas fa-times"></i>
|
||||
</button>
|
||||
<h2 class="text-xl font-bold text-blue-900 mb-4">Thank You!</h2>
|
||||
<p class="text-gray-700">Thank you for your interest! We will contact you as soon as possible.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const demoForm = document.getElementById('demo-form');
|
||||
const thankYouModal = document.getElementById('thank-you-modal');
|
||||
const closeThankYouButton = document.getElementById('close-thankyou');
|
||||
|
||||
demoForm.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const formData = new FormData(demoForm);
|
||||
|
||||
try {
|
||||
const response = await fetch('/schedule', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
thankYouModal.classList.remove('hidden');
|
||||
demoForm.reset();
|
||||
} else {
|
||||
alert(result.message || 'Failed to schedule demo.');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
alert('Error submitting demo request.');
|
||||
}
|
||||
});
|
||||
|
||||
// Existing close modal logic (already in your code, included for clarity)
|
||||
closeThankYouButton.addEventListener('click', () => {
|
||||
thankYouModal.classList.add('hidden');
|
||||
});
|
||||
|
||||
thankYouModal.addEventListener('click', (event) => {
|
||||
if (event.target === thankYouModal) {
|
||||
thankYouModal.classList.add('hidden');
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<script>
|
||||
const modal = document.getElementById('thank-you-modal');
|
||||
const closeButton = document.getElementById('close-thankyou');
|
||||
|
||||
closeButton.addEventListener('click', () => {
|
||||
modal.classList.add('hidden');
|
||||
});
|
||||
|
||||
modal.addEventListener('click', (event) => {
|
||||
if (event.target === modal) {
|
||||
modal.classList.add('hidden');
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const queryForm = document.getElementById('query-form');
|
||||
if (!queryForm) {
|
||||
console.error('Query form with id="query-form" not found!');
|
||||
return;
|
||||
}
|
||||
|
||||
queryForm.addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
const formData = new FormData(this);
|
||||
const data = Object.fromEntries(formData.entries());
|
||||
console.log('Form Data Object:', data);
|
||||
|
||||
// Validate required fields
|
||||
if (!data.email || !data.message) {
|
||||
console.error('Validation failed: Email or message is missing');
|
||||
alert('Please fill in both email and message fields.');
|
||||
return;
|
||||
}
|
||||
|
||||
fetch('/submit', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! Status: ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
console.log('Server response:', data);
|
||||
if (data.success) {
|
||||
document.getElementById('thank-you-modal').classList.remove('hidden');
|
||||
queryForm.reset();
|
||||
} else {
|
||||
alert(data.message || 'Error submitting query');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Fetch error:', error);
|
||||
alert('Error submitting query. Check console for details.');
|
||||
});
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
<!-- Schema Markup for SEO -->
|
||||
<script type="application/ld+json">
|
||||
{
|
||||
"@context": "https://schema.org",
|
||||
"@type": "SoftwareApplication",
|
||||
"name": "AI Infinite",
|
||||
"description": "AI-powered document parser for automating data extraction from PDFs, invoices, passports, and more.",
|
||||
"applicationCategory": "BusinessApplication",
|
||||
"operatingSystem": "Web",
|
||||
"offers": {
|
||||
"@type": "Offer",
|
||||
"price": "Starting at $29/month"
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- AOS JS -->
|
||||
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
|
||||
<script>
|
||||
AOS.init({
|
||||
duration: 800, // Animation duration in milliseconds
|
||||
once: true // Animations happen only once on scroll
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,284 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="description" content="Effortless Invoice Data Extraction with AI Precision. Automate your invoice processing and streamline accounts payable with AI Infinite." />
|
||||
<meta name="keywords" content="invoice extraction, AI OCR, automation, data extraction, AI Infinite" />
|
||||
<title>Invoice Extraction - AI Infinite</title>
|
||||
<!-- Tailwind CSS CDN -->
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<!-- Font Awesome -->
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
|
||||
<!-- AOS CSS -->
|
||||
<link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
|
||||
<link rel="icon" href="{{ url_for('static', filename='logos/ai infinite.jpg') }}" type="image/x-icon">
|
||||
</head>
|
||||
<body class="antialiased text-gray-800">
|
||||
|
||||
|
||||
<nav id="navbar" class="fixed top-0 left-0 w-full bg-[#f7f7f7] backdrop-blur shadow-md z-50">
|
||||
<div class="container mx-auto px-6 py-4 flex items-center">
|
||||
<!-- Logo / Brand -->
|
||||
<a href="{{ url_for('home_logged_in') if logged_in else url_for('index') }}"
|
||||
class="flex items-center space-x-2 hover:opacity-90">
|
||||
<img src="{{ url_for('static', filename='logos/aiinfinite.png') }}"
|
||||
alt="AI Infinite Logo"
|
||||
class="h-12 md:h-16 w-auto" />
|
||||
<span class="text-xl font-bold text-gray-800"></span>
|
||||
</a>
|
||||
<!-- Right‑side Links -->
|
||||
<div class="hidden md:flex items-center ml-auto space-x-12">
|
||||
<a href="{{ url_for('invoice', doc_type='invoice') }}" class="text-gray-700 hover:text-blue-600 font-medium">Invoice</a>
|
||||
<a href="{{ url_for('passport', doc_type='passport') }}" class="text-gray-700 hover:text-blue-600 font-medium">Passport</a>
|
||||
<a href="{{ url_for('pricing') }}" class="text-gray-700 hover:text-blue-600 font-medium">Pricing</a>
|
||||
<a href="{{ url_for('about') }}" class="text-gray-700 hover:text-blue-600 font-medium">About</a>
|
||||
{% if logged_in %}
|
||||
<a href="{{ url_for('dashboard') }}" class="text-gray-700 hover:text-blue-600 font-medium">Dashboard</a>
|
||||
<a href="{{ url_for('logout') }}" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg font-semibold">Logout</a>
|
||||
{% else %}
|
||||
<a href="{{ url_for('login') }}" class="text-gray-700 hover:text-blue-600 font-medium">Log in</a>
|
||||
<a href="{{ url_for('login') }}" class="bg-blue-600 hover:bg-blue-700 text-white px-5 py-2 rounded-lg font-semibold">Get Started</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
<button id="menu-btn" class="md:hidden text-gray-700 focus:outline-none">
|
||||
<i class="fas fa-bars fa-2x"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div id="menu" class="hidden md:hidden bg-[#f7f7f7] backdrop-blur shadow-inner">
|
||||
<div class="flex flex-col space-y-2 px-6 py-4">
|
||||
<a href="{{ url_for('invoice', doc_type='invoice') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Invoice</a>
|
||||
<a href="{{ url_for('passport', doc_type='passport') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Passport</a>
|
||||
<a href="{{ url_for('pricing') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Pricing</a>
|
||||
<a href="{{ url_for('about') }}" class="block text-gray-700 hover:text-blue-600 font-medium">About</a>
|
||||
{% if logged_in %}
|
||||
<a href="{{ url_for('dashboard') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Dashboard</a>
|
||||
<a href="{{ url_for('logout') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Logout</a>
|
||||
{% else %}
|
||||
<a href="{{ url_for('login') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Log in</a>
|
||||
<a href="{{ url_for('login') }}" class="block bg-blue-600 hover:bg-blue-700 text-white px-5 py-2 rounded-lg font-semibold text-center">Get Started</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<!-- Hero Section (always visible, logged‑in or not) -->
|
||||
<section class="relative h-[80vh] flex items-center justify-center text-center text-white pt-20"
|
||||
style="background-image: url('{{ url_for('static', filename='logos/Invoice_bg.png') }}');
|
||||
background-size: cover;
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;">
|
||||
<div class="absolute inset-0 bg-black opacity-50"></div>
|
||||
<div class="relative container mx-auto px-6 z-10" data-aos="fade-up">
|
||||
<h1 class="text-4xl sm:text-5xl font-bold mb-4">
|
||||
Effortless Invoice Data Extraction with AI Precision
|
||||
</h1>
|
||||
<p class="text-lg sm:text-2xl mb-8">
|
||||
Streamline your accounts payable by automating data capture from invoices with unparalleled accuracy.
|
||||
</p>
|
||||
|
||||
{% if logged_in %}
|
||||
<a href="{{ url_for('dashboard') }}"
|
||||
class="bg-blue-600 hover:bg-green-700 text-white font-bold py-3 px-8 rounded text-xl transform hover:scale-105 transition duration-300">
|
||||
Go to Dashboard
|
||||
</a>
|
||||
{% else %}
|
||||
<a href="{{ url_for('login') }}"
|
||||
class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-8 rounded text-xl transform hover:scale-105 transition duration-300">
|
||||
Try It Now
|
||||
</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- How It Works Section -->
|
||||
<section id="how-it-works" class="py-20 bg-gray-50">
|
||||
<div class="container mx-auto px-6">
|
||||
<h2 class="text-3xl font-bold text-center mb-12" data-aos="fade-up">How It Works</h2>
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-12">
|
||||
<div class="text-center" data-aos="fade-up" data-aos-delay="100">
|
||||
<div class="mx-auto p-6 bg-white rounded-full shadow-lg mb-4">
|
||||
<i class="fas fa-upload text-blue-600 text-4xl"></i>
|
||||
</div>
|
||||
<h3 class="text-xl font-semibold mb-2">Upload Invoice</h3>
|
||||
<p>Upload invoices in PDF, JPG, PNG formats.</p>
|
||||
</div>
|
||||
<div class="text-center" data-aos="fade-up" data-aos-delay="200">
|
||||
<div class="mx-auto p-6 bg-white rounded-full shadow-lg mb-4">
|
||||
<i class="fas fa-brain text-blue-600 text-4xl"></i>
|
||||
</div>
|
||||
<h3 class="text-xl font-semibold mb-2">AI & OCR Processing</h3>
|
||||
<p>AI-driven OCR detects and extracts key fields and line items.</p>
|
||||
</div>
|
||||
<div class="text-center" data-aos="fade-up" data-aos-delay="300">
|
||||
<div class="mx-auto p-6 bg-white rounded-full shadow-lg mb-4">
|
||||
<i class="fas fa-file-export text-blue-600 text-4xl"></i>
|
||||
</div>
|
||||
<h3 class="text-xl font-semibold mb-2">Download Data</h3>
|
||||
<p>Get structured JSON or Excel output for your workflows.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Key Features Section -->
|
||||
<section id="features" class="py-20">
|
||||
<div class="container mx-auto px-6">
|
||||
<h2 class="text-3xl font-bold text-center mb-12" data-aos="fade-up">Key Features</h2>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-8">
|
||||
<div class="p-8 bg-white rounded-xl shadow hover:shadow-lg transition" data-aos="fade-up" data-aos-delay="100">
|
||||
<div class="mb-4 text-center"><i class="fas fa-file-alt fa-3x text-blue-600"></i></div>
|
||||
<h3 class="text-xl font-semibold mb-2 text-center">Multi-Format Support</h3>
|
||||
<p class="text-gray-600 text-center">Handles PDFs, scanned images, and digital photos.</p>
|
||||
</div>
|
||||
<div class="p-8 bg-white rounded-xl shadow hover:shadow-lg transition" data-aos="fade-up" data-aos-delay="200">
|
||||
<div class="mb-4 text-center"><i class="fas fa-th-large fa-3x text-blue-600"></i></div>
|
||||
<h3 class="text-xl font-semibold mb-2 text-center">Template-Free AI/OCR</h3>
|
||||
<p class="text-gray-600 text-center">No pre-configured templates—AI adapts to any layout.</p>
|
||||
</div>
|
||||
<div class="p-8 bg-white rounded-xl shadow hover:shadow-lg transition" data-aos="fade-up" data-aos-delay="300">
|
||||
<div class="mb-4 text-center"><i class="fas fa-bullseye fa-3x text-blue-600"></i></div>
|
||||
<h3 class="text-xl font-semibold mb-2 text-center">High Accuracy</h3>
|
||||
<p class="text-gray-600 text-center">Deep-learning + OCR minimizes extraction errors.</p>
|
||||
</div>
|
||||
<div class="p-8 bg-white rounded-xl shadow hover:shadow-lg transition" data-aos="fade-up" data-aos-delay="400">
|
||||
<div class="mb-4 text-center"><i class="fas fa-lock fa-3x text-blue-600"></i></div>
|
||||
<h3 class="text-xl font-semibold mb-2 text-center">Secure & Compliant</h3>
|
||||
<p class="text-gray-600 text-center">End-to-end encryption.</p>
|
||||
</div>
|
||||
<div class="p-8 bg-white rounded-xl shadow hover:shadow-lg transition" data-aos="fade-up" data-aos-delay="500">
|
||||
<div class="mb-4 text-center"><i class="fas fa-plug fa-3x text-blue-600"></i></div>
|
||||
<h3 class="text-xl font-semibold mb-2 text-center">Seamless Integrations</h3>
|
||||
<p class="text-gray-600 text-center">Prebuilt connectors for ERP, CRM, and RPA.</p>
|
||||
</div>
|
||||
<div class="p-8 bg-white rounded-xl shadow hover:shadow-lg transition" data-aos="fade-up" data-aos-delay="600">
|
||||
<div class="mb-4 text-center"><i class="fas fa-cogs fa-3x text-blue-600"></i></div>
|
||||
<h3 class="text-xl font-semibold mb-2 text-center">Custom Fields</h3>
|
||||
<p class="text-gray-600 text-center">Define and extract any fields unique to you.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Benefits Section -->
|
||||
<section id="benefits" class="py-20 bg-gray-50">
|
||||
<div class="container mx-auto px-6">
|
||||
<h2 class="text-3xl font-bold text-center mb-12" data-aos="fade-up">Benefits</h2>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
|
||||
<div class="text-center" data-aos="fade-up" data-aos-delay="100">
|
||||
<i class="fas fa-clock fa-3x text-blue-600 mb-4"></i>
|
||||
<h3 class="text-xl font-semibold mb-2">Save Time</h3>
|
||||
<p>Eliminate manual entry and accelerate workflows.</p>
|
||||
</div>
|
||||
<div class="text-center" data-aos="fade-up" data-aos-delay="200">
|
||||
<i class="fas fa-dollar-sign fa-3x text-blue-600 mb-4"></i>
|
||||
<h3 class="text-xl font-semibold mb-2">Reduce Costs</h3>
|
||||
<p>Minimize errors and avoid late-payment penalties.</p>
|
||||
</div>
|
||||
<div class="text-center" data-aos="fade-up" data-aos-delay="300">
|
||||
<i class="fas fa-chart-line fa-3x text-blue-600 mb-4"></i>
|
||||
<h3 class="text-xl font-semibold mb-2">Scale Effortlessly</h3>
|
||||
<p>Process thousands of invoices in minutes.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- FAQ Section -->
|
||||
<section id="faq" class="py-20">
|
||||
<div class="container mx-auto px-6 lg:flex lg:space-x-12">
|
||||
<div class="lg:w-1/2" data-aos="fade-right">
|
||||
<h2 class="text-3xl font-bold mb-6">Frequently Asked Questions</h2>
|
||||
<div class="space-y-4">
|
||||
<details class="bg-white p-4 rounded-lg shadow">
|
||||
<summary class="font-semibold cursor-pointer">Which file types are supported?</summary>
|
||||
<p class="mt-2 text-gray-600">PNG, JPG, PDF, and more.</p>
|
||||
</details>
|
||||
<details class="bg-white p-4 rounded-lg shadow">
|
||||
<summary class="font-semibold cursor-pointer">How secure is my data?</summary>
|
||||
<p class="mt-2 text-gray-600">Data is encrypted at rest and in transit.</p>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
<div class="lg:w-1/2 mt-12 lg:mt-0" data-aos="fade-left">
|
||||
<h2 class="text-3xl font-bold mb-6">Talk to Sales</h2>
|
||||
<form action="https://example.com/contact" method="POST" class="space-y-4">
|
||||
<input type="text" name="name" placeholder="Name*" required class="w-full p-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
<input type="email" name="email" placeholder="Email*" required class="w-full p-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
<input type="tel" name="phone" placeholder="Phone" class="w-full p-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
<textarea name="message" rows="4" placeholder="Message" class="w-full p-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
|
||||
<button type="submit" class="w-full bg-blue-600 text-white font-semibold py-3 rounded-lg hover:bg-blue-700 transition">Submit</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Footer Section -->
|
||||
<footer class="bg-gray-800 text-gray-200 py-8">
|
||||
<div class="container mx-auto px-4 text-center">
|
||||
<p class="mb-2">© 2025 AI Infinite. All rights reserved.</p>
|
||||
<p class="mb-2">
|
||||
<a href="#features" class="hover:underline mx-2">Features</a>|
|
||||
<a href="#benefits" class="hover:underline mx-2">Benefits</a>|
|
||||
<a href="#faq" class="hover:underline mx-2">FAQ</a>|
|
||||
<a href="#" class="hover:underline mx-2">Blog</a>|
|
||||
<a href="#" class="hover:underline mx-2">Help Center</a>|
|
||||
<a href="#" class="hover:underline mx-2">API</a>
|
||||
</p>
|
||||
<p class="mb-2">
|
||||
<a href="#" class="hover:underline mx-2">Terms</a>|
|
||||
<a href="#" class="hover:underline mx-2">Privacy Policy</a>|
|
||||
<a href="#" class="hover:underline mx-2">Security</a>|
|
||||
<a href="#" class="hover:underline mx-2">GDPR</a>
|
||||
</p>
|
||||
<p>
|
||||
Follow us:
|
||||
<a href="#" class="mx-2 transform hover:scale-125 transition duration-300"><i class="fab fa-twitter"></i></a>
|
||||
<a href="#" class="mx-2 transform hover:scale-125 transition duration-300"><i class="fab fa-linkedin"></i></a>
|
||||
<a href="#" class="mx-2 transform hover:scale-125 transition duration-300"><i class="fab fa-facebook"></i></a>
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<!-- Schema Markup for SEO -->
|
||||
<script type="application/ld+json">
|
||||
{
|
||||
"@context": "https://schema.org",
|
||||
"@type": "SoftwareApplication",
|
||||
"name": "AI Infinite",
|
||||
"description": "AI-powered document parser for automating data extraction from PDFs, invoices, passports, and more.",
|
||||
"applicationCategory": "BusinessApplication",
|
||||
"operatingSystem": "Web",
|
||||
"offers": {
|
||||
"@type": "Offer",
|
||||
"price": "Starting at $29/month"
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Scripts -->
|
||||
<script>
|
||||
// Mobile menu toggle
|
||||
document.getElementById('menu-btn').addEventListener('click', () => {
|
||||
document.getElementById('menu').classList.toggle('hidden');
|
||||
});
|
||||
// Navbar shadow on scroll (optional)
|
||||
const navbar = document.getElementById('navbar');
|
||||
window.addEventListener('scroll', () => {
|
||||
if (window.scrollY > 50) {
|
||||
navbar.classList.add('shadow-lg');
|
||||
} else {
|
||||
navbar.classList.remove('shadow-lg');
|
||||
}
|
||||
});
|
||||
</script>
|
||||
<!-- AOS JS -->
|
||||
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
|
||||
<script>
|
||||
AOS.init({
|
||||
duration: 800,
|
||||
once: true
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,680 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Manual Item Codes - AI Infinite</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||
<style>
|
||||
:root {
|
||||
--primary-color: #007bff;
|
||||
--background-light: #f8f9fa;
|
||||
--text-dark: #333;
|
||||
--white: #fff;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
color: var(--text-dark);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
line-height: 1.6;
|
||||
background-color: var(--background-light);
|
||||
}
|
||||
|
||||
.navbar {
|
||||
background-color: #f7f7f7;
|
||||
padding: 1rem;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.navbar-brand {
|
||||
font-size: 1.5rem;
|
||||
font-weight: bold;
|
||||
color: var(--primary-color);
|
||||
text-decoration: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.navbar-toggler {
|
||||
padding: 0.25rem 0.5rem;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.navbar-toggler-icon {
|
||||
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba(0, 123, 255, 1)' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
|
||||
}
|
||||
|
||||
.main-container {
|
||||
display: flex;
|
||||
min-height: calc(100vh - 60px);
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
width: 250px;
|
||||
background-color: var(--white);
|
||||
border-right: 1px solid #dee2e6;
|
||||
padding: 1.5rem;
|
||||
position: fixed;
|
||||
height: 100%;
|
||||
z-index: 1000;
|
||||
transform: translateX(-100%);
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
.sidebar.active {
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
.sidebar .nav-link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
color: var(--text-dark);
|
||||
padding: 0.75rem 1rem;
|
||||
margin: 0.3rem 0;
|
||||
border-radius: 5px;
|
||||
text-decoration: none;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
|
||||
.sidebar .nav-link:hover {
|
||||
background-color: var(--background-light);
|
||||
}
|
||||
|
||||
.sidebar .nav-link.active {
|
||||
background-color: #e9ecef;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 1000px;
|
||||
margin: 2rem auto;
|
||||
padding: 0 1rem;
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.card {
|
||||
background-color: var(--white);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
|
||||
padding: 1.5rem;
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: 1.5rem;
|
||||
margin-bottom: 1rem;
|
||||
color: var(--text-dark);
|
||||
}
|
||||
|
||||
.form-label {
|
||||
font-weight: 500;
|
||||
color: var(--text-dark);
|
||||
}
|
||||
|
||||
.form-control {
|
||||
border-radius: 5px;
|
||||
border: 1px solid #ccc;
|
||||
padding: 0.75rem;
|
||||
width: 100%;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background-color: var(--primary-color);
|
||||
color: var(--white);
|
||||
padding: 0.75rem 1.5rem;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
font-weight: bold;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background-color: #0056b3;
|
||||
}
|
||||
|
||||
.btn-primary:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background-color: #6c757d;
|
||||
color: var(--white);
|
||||
padding: 0.6rem 1.2rem;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background-color: #5a6268;
|
||||
}
|
||||
|
||||
.loading-container {
|
||||
display: none;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 2rem 0;
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
border-radius: 50%;
|
||||
background-color: var(--primary-color);
|
||||
animation: bounce 1.5s infinite ease-in-out;
|
||||
}
|
||||
|
||||
.dot:nth-child(1) { animation-delay: 0s; }
|
||||
.dot:nth-child(2) { animation-delay: 0.2s; }
|
||||
.dot:nth-child(3) { animation-delay: 0.4s; }
|
||||
|
||||
@keyframes bounce {
|
||||
0%, 100% { transform: translateY(0); }
|
||||
50% { transform: translateY(-10px); }
|
||||
}
|
||||
|
||||
.items-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-top: 1rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.items-table th, .items-table td {
|
||||
padding: 10px 12px;
|
||||
border-bottom: 1px solid #e9ecef;
|
||||
text-align: left;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.items-table th {
|
||||
background-color: var(--background-light);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.code-input {
|
||||
width: 100%;
|
||||
min-width: 130px;
|
||||
padding: 6px 10px;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 5px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.code-input:focus {
|
||||
outline: none;
|
||||
border-color: var(--primary-color);
|
||||
box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.15);
|
||||
}
|
||||
|
||||
.code-input.empty {
|
||||
border-color: #f0ad4e;
|
||||
background: #fffbea;
|
||||
}
|
||||
|
||||
.badge-source {
|
||||
display: inline-block;
|
||||
padding: 4px 10px;
|
||||
border-radius: 12px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.badge-invoice { background: #d1e7ff; color: #084298; }
|
||||
.badge-matched { background: #d1f5e0; color: #0f5132; }
|
||||
.badge-manual { background: #e2d9f3; color: #4b2a85; }
|
||||
.badge-missing { background: #f8d7da; color: #842029; }
|
||||
.badge-edited { background: #fff3cd; color: #856404; }
|
||||
|
||||
.summary-badge {
|
||||
display: inline-block;
|
||||
padding: 6px 14px;
|
||||
border-radius: 20px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.file-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-top: 10px;
|
||||
padding: 6px 12px;
|
||||
background: var(--background-light);
|
||||
border-radius: 20px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.file-chip button {
|
||||
border: none;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
color: #888;
|
||||
}
|
||||
|
||||
.file-chip button:hover { color: #c33; }
|
||||
|
||||
.table-scroll { overflow-x: auto; }
|
||||
|
||||
.json-viewer {
|
||||
background: #1e1e2e;
|
||||
color: #cdd6f4;
|
||||
padding: 16px;
|
||||
border-radius: 8px;
|
||||
margin-top: 15px;
|
||||
font-family: Consolas, 'Liberation Mono', Menlo, monospace;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.5;
|
||||
max-height: 500px;
|
||||
overflow: auto;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.json-key { color: #89b4fa; }
|
||||
.json-string { color: #a6e3a1; }
|
||||
.json-number { color: #fab387; }
|
||||
.json-boolean { color: #cba6f7; }
|
||||
.json-null { color: #f38ba8; }
|
||||
|
||||
.hint { color: #888; font-size: 0.85rem; margin: 10px 0; }
|
||||
.hidden { display: none !important; }
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.sidebar { width: 220px; }
|
||||
.container { max-width: 95%; margin: 1rem auto; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<nav class="navbar">
|
||||
<div class="container-fluid">
|
||||
<button class="navbar-toggler" id="sidebarToggle"><span class="navbar-toggler-icon"></span></button>
|
||||
<a href="{{ url_for('index') }}" class="navbar-brand">
|
||||
<a src="{{ url_for('static', filename='logos/aiinfinite.png') }}" alt="AI Infinite Logo"
|
||||
style="height: 40px;">
|
||||
</a>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="main-container">
|
||||
<div class="sidebar">
|
||||
<div class="nav flex-column">
|
||||
<a class="nav-link" href="{{ url_for('home_logged_in') }}"><i class="fas fa-home"></i> Home</a>
|
||||
<a class="nav-link" href="{{ url_for('dashboard') }}"><i class="fas fa-tachometer-alt"></i> Dashboard Overview</a>
|
||||
<a class="nav-link" href="{{ url_for('view_history') }}"><i class="fas fa-history"></i> View Document History</a>
|
||||
<a class="nav-link active" href="{{ url_for('manual_item_codes_page') }}"><i class="fas fa-edit"></i> Manual Item Codes</a>
|
||||
<a class="nav-link" href="{{ url_for('logout') }}"><i class="fas fa-sign-out-alt"></i> Logout</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<div id="pageMessage"></div>
|
||||
|
||||
<!-- Upload Card -->
|
||||
<div class="card">
|
||||
<h5 class="card-title">Upload Invoice & Add Item Codes</h5>
|
||||
<p class="hint" style="margin-top: -8px;">Choose a file, extract it, then add or fix item codes for any items that need one.</p>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="manualFile" class="form-label">Invoice File (PDF or Image)</label>
|
||||
<input type="file" class="form-control" id="manualFile" accept=".pdf,.png,.jpg,.jpeg">
|
||||
<div class="file-chip hidden" id="fileChip">
|
||||
<span id="fileChipName"></span>
|
||||
<button type="button" onclick="clearFile()" title="Remove">✕</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3 form-check">
|
||||
<input type="checkbox" class="form-check-input" id="useDrugList" checked>
|
||||
<label class="form-check-label" for="useDrugList">
|
||||
Try to auto-fill item codes from the drug list (drug_list.csv) first
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<button type="button" class="btn btn-primary" id="extractBtn" onclick="extractInvoice()" disabled>
|
||||
<i class="fas fa-magic"></i> Extract Invoice
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Loading -->
|
||||
<div class="loading-container" id="loadingContainer">
|
||||
<div class="dot"></div>
|
||||
<div class="dot"></div>
|
||||
<div class="dot"></div>
|
||||
</div>
|
||||
|
||||
<!-- Results -->
|
||||
<div class="card hidden" id="resultsCard">
|
||||
<div class="d-flex justify-content-between align-items-center flex-wrap" style="gap: 10px;">
|
||||
<h5 class="card-title" style="margin-bottom: 0;">Item Codes</h5>
|
||||
<span id="summaryBadge"></span>
|
||||
</div>
|
||||
|
||||
<p class="hint">Rows highlighted in yellow have no item code yet. Type a code, then click Save. Press Enter to move to the next row.</p>
|
||||
|
||||
<div class="table-scroll">
|
||||
<table class="items-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>Description</th>
|
||||
<th>Qty</th>
|
||||
<th>Unit Price</th>
|
||||
<th>Item Code</th>
|
||||
<th>Source</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="itemsBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="d-flex flex-wrap" style="gap: 10px; margin-top: 1.25rem;">
|
||||
<button type="button" class="btn btn-primary" id="saveBtn" onclick="saveItemCodes()" disabled>
|
||||
<i class="fas fa-save"></i> Save Item Codes
|
||||
</button>
|
||||
<button type="button" class="btn btn-secondary" id="jsonToggleBtn" onclick="toggleJsonView()">
|
||||
<i class="fas fa-code"></i> Show JSON
|
||||
</button>
|
||||
<button type="button" class="btn btn-secondary" onclick="resetPage()">
|
||||
<i class="fas fa-redo"></i> Upload Another
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<pre class="json-viewer hidden" id="jsonViewer"></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.getElementById('sidebarToggle').addEventListener('click', function () {
|
||||
document.querySelector('.sidebar').classList.toggle('active');
|
||||
});
|
||||
|
||||
let selectedFile = null;
|
||||
let extractedData = null;
|
||||
let extractionId = null;
|
||||
|
||||
document.getElementById('manualFile').addEventListener('change', function (e) {
|
||||
if (e.target.files.length > 0) {
|
||||
setFile(e.target.files[0]);
|
||||
}
|
||||
});
|
||||
|
||||
function setFile(file) {
|
||||
const validExt = /\.(pdf|png|jpe?g)$/i;
|
||||
if (!validExt.test(file.name)) {
|
||||
showMessage('Please choose a PDF, PNG or JPG file.', 'danger');
|
||||
return;
|
||||
}
|
||||
selectedFile = file;
|
||||
hideMessage();
|
||||
document.getElementById('fileChipName').textContent = file.name;
|
||||
document.getElementById('fileChip').classList.remove('hidden');
|
||||
document.getElementById('extractBtn').disabled = false;
|
||||
}
|
||||
|
||||
function clearFile() {
|
||||
selectedFile = null;
|
||||
document.getElementById('manualFile').value = '';
|
||||
document.getElementById('fileChip').classList.add('hidden');
|
||||
document.getElementById('extractBtn').disabled = true;
|
||||
}
|
||||
|
||||
function showMessage(text, type) {
|
||||
document.getElementById('pageMessage').innerHTML =
|
||||
`<div class="alert alert-${type} alert-dismissible fade show" role="alert">
|
||||
<strong>${escapeHtml(text)}</strong>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function hideMessage() {
|
||||
document.getElementById('pageMessage').innerHTML = '';
|
||||
}
|
||||
|
||||
function escapeHtml(s) {
|
||||
const d = document.createElement('div');
|
||||
d.textContent = s;
|
||||
return d.innerHTML;
|
||||
}
|
||||
|
||||
async function extractInvoice() {
|
||||
if (!selectedFile) return;
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file', selectedFile);
|
||||
formData.append('use_drug_list', document.getElementById('useDrugList').checked ? 'true' : 'false');
|
||||
|
||||
document.getElementById('loadingContainer').style.display = 'flex';
|
||||
document.getElementById('resultsCard').classList.add('hidden');
|
||||
document.getElementById('extractBtn').disabled = true;
|
||||
hideMessage();
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/manual-extract', { method: 'POST', body: formData });
|
||||
const result = await response.json();
|
||||
|
||||
if (response.ok && result.success) {
|
||||
extractedData = result.data;
|
||||
extractionId = result.extraction_id || null;
|
||||
renderResults();
|
||||
document.getElementById('resultsCard').classList.remove('hidden');
|
||||
|
||||
if (!extractionId) {
|
||||
showMessage('Extracted, but this could not be saved to history — item codes cannot be saved.', 'warning');
|
||||
} else {
|
||||
showMessage('Invoice extracted. Add or fix item codes below, then click Save.', 'success');
|
||||
}
|
||||
} else {
|
||||
showMessage(result.error || 'Extraction failed.', 'danger');
|
||||
}
|
||||
} catch (err) {
|
||||
showMessage('Network error. Please try again.', 'danger');
|
||||
} finally {
|
||||
document.getElementById('loadingContainer').style.display = 'none';
|
||||
document.getElementById('extractBtn').disabled = !selectedFile;
|
||||
}
|
||||
}
|
||||
|
||||
function sourceBadge(source) {
|
||||
const map = {
|
||||
invoice: ['badge-invoice', 'On Invoice'],
|
||||
drug_list_match: ['badge-matched', 'Matched'],
|
||||
manual: ['badge-manual', 'Manual'],
|
||||
not_found: ['badge-missing', 'Not Found'],
|
||||
};
|
||||
const [cls, label] = map[source] || map.not_found;
|
||||
const span = document.createElement('span');
|
||||
span.className = `badge-source ${cls}`;
|
||||
span.textContent = label;
|
||||
return span;
|
||||
}
|
||||
|
||||
function renderResults() {
|
||||
const items = Array.isArray(extractedData.items) ? extractedData.items : [];
|
||||
const tbody = document.getElementById('itemsBody');
|
||||
tbody.replaceChildren();
|
||||
|
||||
items.forEach((rawItem, i) => {
|
||||
const item = (rawItem && typeof rawItem === 'object') ? rawItem : {};
|
||||
const code = item.item_code ? String(item.item_code).trim() : '';
|
||||
|
||||
const tr = document.createElement('tr');
|
||||
tr.dataset.source = item.item_code_source || 'not_found';
|
||||
|
||||
[i + 1, item.description, item.quantity, item.unit_price].forEach(val => {
|
||||
const td = document.createElement('td');
|
||||
td.textContent = (val === undefined || val === null || val === '') ? '-' : val;
|
||||
tr.appendChild(td);
|
||||
});
|
||||
|
||||
const codeTd = document.createElement('td');
|
||||
const input = document.createElement('input');
|
||||
input.type = 'text';
|
||||
input.className = 'code-input' + (code ? '' : ' empty');
|
||||
input.value = code;
|
||||
input.placeholder = 'Enter item code';
|
||||
input.maxLength = 50;
|
||||
input.dataset.index = i;
|
||||
input.dataset.original = code;
|
||||
input.addEventListener('input', onCodeInput);
|
||||
input.addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
const inputs = [...document.querySelectorAll('#itemsBody .code-input')];
|
||||
const next = inputs[inputs.indexOf(input) + 1];
|
||||
if (next) next.focus();
|
||||
}
|
||||
});
|
||||
codeTd.appendChild(input);
|
||||
tr.appendChild(codeTd);
|
||||
|
||||
const statusTd = document.createElement('td');
|
||||
statusTd.className = 'status-cell';
|
||||
statusTd.appendChild(sourceBadge(tr.dataset.source));
|
||||
tr.appendChild(statusTd);
|
||||
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
|
||||
updateSummary();
|
||||
refreshJson();
|
||||
}
|
||||
|
||||
function onCodeInput(e) {
|
||||
const input = e.target;
|
||||
const value = input.value.trim();
|
||||
const tr = input.closest('tr');
|
||||
const statusCell = tr.querySelector('.status-cell');
|
||||
|
||||
input.classList.toggle('empty', value === '');
|
||||
|
||||
if (value !== input.dataset.original) {
|
||||
const span = document.createElement('span');
|
||||
span.className = 'badge-source badge-edited';
|
||||
span.textContent = 'Edited';
|
||||
statusCell.replaceChildren(span);
|
||||
} else {
|
||||
statusCell.replaceChildren(sourceBadge(tr.dataset.source));
|
||||
}
|
||||
|
||||
updateSummary();
|
||||
refreshJson();
|
||||
}
|
||||
|
||||
function updateSummary() {
|
||||
const inputs = [...document.querySelectorAll('#itemsBody .code-input')];
|
||||
const total = inputs.length;
|
||||
const withCode = inputs.filter(i => i.value.trim() !== '').length;
|
||||
const unsaved = inputs.filter(i => i.value.trim() !== i.dataset.original).length;
|
||||
|
||||
const badge = document.getElementById('summaryBadge');
|
||||
if (total > 0 && withCode === total) {
|
||||
badge.innerHTML = '<span class="summary-badge badge-matched">✓ All items have codes</span>';
|
||||
} else {
|
||||
badge.innerHTML = `<span class="summary-badge badge-missing">${total - withCode} of ${total} missing codes</span>`;
|
||||
}
|
||||
|
||||
const saveBtn = document.getElementById('saveBtn');
|
||||
saveBtn.disabled = unsaved === 0 || !extractionId;
|
||||
saveBtn.innerHTML = unsaved > 0
|
||||
? `<i class="fas fa-save"></i> Save Item Codes (${unsaved})`
|
||||
: `<i class="fas fa-save"></i> Save Item Codes`;
|
||||
}
|
||||
|
||||
async function saveItemCodes() {
|
||||
if (!extractionId) {
|
||||
showMessage('This extraction was not saved to history, so codes cannot be saved.', 'danger');
|
||||
return;
|
||||
}
|
||||
|
||||
const item_codes = [...document.querySelectorAll('#itemsBody .code-input')]
|
||||
.filter(i => i.value.trim() !== i.dataset.original)
|
||||
.map(i => ({ index: Number(i.dataset.index), item_code: i.value.trim() }));
|
||||
|
||||
if (item_codes.length === 0) return;
|
||||
|
||||
const saveBtn = document.getElementById('saveBtn');
|
||||
saveBtn.disabled = true;
|
||||
saveBtn.textContent = 'Saving...';
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/extraction/${extractionId}/item-codes`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ item_codes })
|
||||
});
|
||||
const result = await response.json();
|
||||
|
||||
if (response.ok && result.success) {
|
||||
extractedData = result.data;
|
||||
renderResults();
|
||||
showMessage(`Saved ${result.updated} item code(s).`, 'success');
|
||||
} else {
|
||||
showMessage(result.error || 'Failed to save item codes.', 'danger');
|
||||
}
|
||||
} catch (err) {
|
||||
showMessage('Network error. Please try again.', 'danger');
|
||||
} finally {
|
||||
updateSummary();
|
||||
}
|
||||
}
|
||||
|
||||
function highlightJson(obj) {
|
||||
const json = JSON.stringify(obj, null, 2)
|
||||
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
return json.replace(
|
||||
/("(?:\\u[a-fA-F0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(?:true|false|null)\b|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g,
|
||||
(match) => {
|
||||
let cls = 'json-number';
|
||||
if (match.startsWith('"')) cls = match.endsWith(':') ? 'json-key' : 'json-string';
|
||||
else if (match === 'true' || match === 'false') cls = 'json-boolean';
|
||||
else if (match === 'null') cls = 'json-null';
|
||||
return `<span class="${cls}">${match}</span>`;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
function refreshJson() {
|
||||
const viewer = document.getElementById('jsonViewer');
|
||||
if (viewer.classList.contains('hidden')) return;
|
||||
viewer.innerHTML = extractedData ? highlightJson(extractedData) : '';
|
||||
}
|
||||
|
||||
function toggleJsonView() {
|
||||
const viewer = document.getElementById('jsonViewer');
|
||||
const nowHidden = viewer.classList.toggle('hidden');
|
||||
document.getElementById('jsonToggleBtn').innerHTML = nowHidden
|
||||
? '<i class="fas fa-code"></i> Show JSON'
|
||||
: '<i class="fas fa-code"></i> Hide JSON';
|
||||
refreshJson();
|
||||
}
|
||||
|
||||
function resetPage() {
|
||||
const saveBtn = document.getElementById('saveBtn');
|
||||
if (!saveBtn.disabled && !confirm('You have unsaved item codes. Discard them?')) {
|
||||
return;
|
||||
}
|
||||
clearFile();
|
||||
extractedData = null;
|
||||
extractionId = null;
|
||||
document.getElementById('resultsCard').classList.add('hidden');
|
||||
document.getElementById('jsonViewer').classList.add('hidden');
|
||||
document.getElementById('jsonToggleBtn').innerHTML = '<i class="fas fa-code"></i> Show JSON';
|
||||
hideMessage();
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,268 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="description" content="Effortless Passport Data Extraction with AI Precision. Automate your passport processing and streamline your workflow with AI Infinite." />
|
||||
<meta name="keywords" content="passport extraction, AI OCR, automation, data extraction, AI Infinite" />
|
||||
<title>Passport Extraction - AI Infinite</title>
|
||||
<!-- Tailwind CSS CDN -->
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<!-- Font Awesome -->
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
|
||||
<!-- AOS CSS -->
|
||||
<link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
|
||||
<link rel="icon" href="{{ url_for('static', filename='logos/ai infinite.jpg') }}" type="image/x-icon">
|
||||
</head>
|
||||
<body class="antialiased text-gray-800">
|
||||
|
||||
<!-- Updated Navbar -->
|
||||
<nav id="navbar" class="fixed top-0 left-0 w-full bg-[#f7f7f7] backdrop-blur shadow-md z-50">
|
||||
<div class="container mx-auto px-6 py-4 flex items-center">
|
||||
<!-- Logo / Brand -->
|
||||
<a href="{{ url_for('home_logged_in') if logged_in else url_for('index') }}" class="flex items-center space-x-2 hover:opacity-90">
|
||||
<img src="{{ url_for('static', filename='logos/aiinfinite.png') }}" alt="AI Infinite Logo" class="h-12 md:h-16 w-auto" />
|
||||
<span class="text-xl font-bold text-gray-800"></span>
|
||||
</a>
|
||||
|
||||
<!-- Combined Right-side Links -->
|
||||
<div class="hidden md:flex items-center ml-auto space-x-12">
|
||||
<a href="{{ url_for('invoice', doc_type='invoice') }}" class="text-gray-700 hover:text-blue-600 font-medium">Invoice</a>
|
||||
<a href="{{ url_for('passport', doc_type='passport') }}" class="text-gray-700 hover:text-blue-600 font-medium">Passport</a>
|
||||
<a href="{{ url_for('pricing') }}" class="text-gray-700 hover:text-blue-600 font-medium">Pricing</a>
|
||||
<a href="{{ url_for('about') }}" class="text-gray-700 hover:text-blue-600 font-medium">About</a>
|
||||
{% if logged_in %}
|
||||
<a href="{{ url_for('dashboard') }}" class="text-gray-700 hover:text-blue-600 font-medium">Dashboard</a>
|
||||
<a href="{{ url_for('logout') }}" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg font-semibold">Logout</a>
|
||||
{% else %}
|
||||
<a href="{{ url_for('login') }}" class="text-gray-700 hover:text-blue-600 font-medium">Log in</a>
|
||||
<a href="{{ url_for('login') }}" class="bg-blue-600 hover:bg-blue-700 text-white px-5 py-2 rounded-lg font-semibold">Get Started</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- Mobile Menu Button -->
|
||||
<button id="menu-btn" class="md:hidden text-gray-700 focus:outline-none">
|
||||
<i class="fas fa-bars fa-2x"></i>
|
||||
</button>
|
||||
</div>
|
||||
<!-- Mobile Menu Content -->
|
||||
<div id="menu" class="hidden md:hidden bg-[#f7f7f7] backdrop-blur shadow-inner">
|
||||
<div class="flex flex-col space-y-2 px-6 py-4">
|
||||
<a href="{{ url_for('invoice', doc_type='invoice') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Invoice</a>
|
||||
<a href="{{ url_for('passport', doc_type='passport') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Passport</a>
|
||||
<a href="{{ url_for('pricing') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Pricing</a>
|
||||
<a href="{{ url_for('about') }}" class="block text-gray-700 hover:text-blue-600 font-medium">About</a>
|
||||
{% if logged_in %}
|
||||
<a href="{{ url_for('dashboard') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Dashboard</a>
|
||||
<a href="{{ url_for('logout') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Logout</a>
|
||||
{% else %}
|
||||
<a href="{{ url_for('login') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Log in</a>
|
||||
<a href="{{ url_for('login') }}" class="block bg-blue-600 hover:bg-blue-700 text-white px-5 py-2 rounded-lg font-semibold text-center">Get Started</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<!-- Hero Section (Passport page) -->
|
||||
<section class="relative h-[80vh] flex items-center justify-center text-center text-white pt-20"
|
||||
style="background-image: url('{{ url_for('static', filename='logos/Invoice_bg.png') }}');
|
||||
background-size: cover;
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;">
|
||||
<div class="absolute inset-0 bg-black opacity-50"></div>
|
||||
<div class="relative container mx-auto px-6 z-10" data-aos="fade-up">
|
||||
<h1 class="text-4xl sm:text-5xl font-bold mb-4">
|
||||
Fast, Accurate Passport OCR You Can Trust
|
||||
</h1>
|
||||
<p class="text-lg sm:text-2xl mb-8">
|
||||
From scanned passports to structured data in seconds—AI Infinite does the heavy lifting.
|
||||
</p>
|
||||
|
||||
{% if logged_in %}
|
||||
<a href="{{ url_for('dashboard') }}"
|
||||
class="bg-blue-600 hover:bg-green-700 text-white font-bold py-3 px-8 rounded text-xl transform hover:scale-105 transition duration-300">
|
||||
Go to Dashboard
|
||||
</a>
|
||||
{% else %}
|
||||
<a href="{{ url_for('login') }}"
|
||||
class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-8 rounded text-xl transform hover:scale-105 transition duration-300">
|
||||
Try It Now
|
||||
</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
<!-- How It Works -->
|
||||
<section id="how-it-works" class="py-20 bg-gray-50">
|
||||
<div class="container mx-auto px-6">
|
||||
<h2 class="text-4xl font-bold text-center mb-12" data-aos="fade-up">How It Works</h2>
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-12">
|
||||
<div class="text-center" data-aos="fade-up" data-aos-delay="100">
|
||||
<div class="mx-auto p-6 bg-white rounded-full shadow-lg mb-4">
|
||||
<i class="fas fa-passport text-blue-600 text-4xl"></i>
|
||||
</div>
|
||||
<h3 class="text-2xl font-semibold mb-2">Upload Passport</h3>
|
||||
<p>Upload passport images or PDFs.</p>
|
||||
</div>
|
||||
<div class="text-center" data-aos="fade-up" data-aos-delay="200">
|
||||
<div class="mx-auto p-6 bg-white rounded-full shadow-lg mb-4">
|
||||
<i class="fas fa-brain text-blue-600 text-4xl"></i>
|
||||
</div>
|
||||
<h3 class="text-2xl font-semibold mb-2">AI Processing</h3>
|
||||
<p>AI extracts key details like name, date of birth, and passport number.</p>
|
||||
</div>
|
||||
<div class="text-center" data-aos="fade-up" data-aos-delay="300">
|
||||
<div class="mx-auto p-6 bg-white rounded-full shadow-lg mb-4">
|
||||
<i class="fas fa-database text-blue-600 text-4xl"></i>
|
||||
</div>
|
||||
<h3 class="text-2xl font-semibold mb-2">Get Structured Data</h3>
|
||||
<p>Receive extracted data in JSON or Excel format.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Key Features -->
|
||||
<section id="features" class="py-20">
|
||||
<div class="container mx-auto px-6">
|
||||
<h2 class="text-4xl font-bold text-center mb-12" data-aos="fade-up">Key Features</h2>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-8">
|
||||
<!-- Feature cards identical to Invoice page -->
|
||||
<div class="p-8 bg-white rounded-xl shadow hover:shadow-lg transition" data-aos="fade-up" data-aos-delay="100">
|
||||
<div class="mb-4 text-center"><i class="fas fa-file-alt fa-3x text-blue-600"></i></div>
|
||||
<h3 class="text-2xl font-semibold mb-2 text-center">Multi-Format Support</h3>
|
||||
<p class="text-gray-600 text-center">Handles images and PDFs from any device.</p>
|
||||
</div>
|
||||
<div class="p-8 bg-white rounded-xl shadow hover:shadow-lg transition" data-aos="fade-up" data-aos-delay="200">
|
||||
<div class="mb-4 text-center"><i class="fas fa-th-large fa-3x text-blue-600"></i></div>
|
||||
<h3 class="text-2xl font-semibold mb-2 text-center">Template-Free AI/OCR</h3>
|
||||
<p class="text-gray-600 text-center">Adapts to any passport layout automatically.</p>
|
||||
</div>
|
||||
<div class="p-8 bg-white rounded-xl shadow hover:shadow-lg transition" data-aos="fade-up" data-aos-delay="300">
|
||||
<div class="mb-4 text-center"><i class="fas fa-bullseye fa-3x text-blue-600"></i></div>
|
||||
<h3 class="text-2xl font-semibold mb-2 text-center">High Accuracy</h3>
|
||||
<p class="text-gray-600 text-center">Deep‑learning + OCR minimizes extraction errors.</p>
|
||||
</div>
|
||||
<div class="p-8 bg-white rounded-xl shadow hover:shadow-lg transition" data-aos="fade-up" data-aos-delay="400">
|
||||
<div class="mb-4 text-center"><i class="fas fa-lock fa-3x text-blue-600"></i></div>
|
||||
<h3 class="text-2xl font-semibold mb-2 text-center">Secure & Compliant</h3>
|
||||
<p class="text-gray-600 text-center">End‑to‑end encryption and SOC2/ISO27001 compliant.</p>
|
||||
</div>
|
||||
<div class="p-8 bg-white rounded-xl shadow hover:shadow-lg transition" data-aos="fade-up" data-aos-delay="500">
|
||||
<div class="mb-4 text-center"><i class="fas fa-plug fa-3x text-blue-600"></i></div>
|
||||
<h3 class="text-2xl font-semibold mb-2 text-center">Seamless Integrations</h3>
|
||||
<p class="text-gray-600 text-center">Connect to your ERP, CRM, or RPA tools easily.</p>
|
||||
</div>
|
||||
<div class="p-8 bg-white rounded-xl shadow hover:shadow-lg transition" data-aos="fade-up" data-aos-delay="600">
|
||||
<div class="mb-4 text-center"><i class="fas fa-cogs fa-3x text-blue-600"></i></div>
|
||||
<h3 class="text-2xl font-semibold mb-2 text-center">Custom Field Extraction</h3>
|
||||
<p class="text-gray-600 text-center">Define and pull any fields unique to your process.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Benefits -->
|
||||
<section id="benefits" class="py-20 bg-gray-50">
|
||||
<div class="container mx-auto px-6">
|
||||
<h2 class="text-4xl font-bold text-center mb-12" data-aos="fade-up">Benefits</h2>
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-8">
|
||||
<div class="text-center" data-aos="fade-up" data-aos-delay="100">
|
||||
<i class="fas fa-clock fa-3x text-blue-600 mb-4"></i>
|
||||
<h3 class="text-2xl font-semibold mb-2">Save Time</h3>
|
||||
<p>Automate passport data entry and speed up processing.</p>
|
||||
</div>
|
||||
<div class="text-center" data-aos="fade-up" data-aos-delay="200">
|
||||
<i class="fas fa-check-circle fa-3x text-blue-600 mb-4"></i>
|
||||
<h3 class="text-2xl font-semibold mb-2">Reduce Errors</h3>
|
||||
<p>Minimize manual mistakes with AI precision.</p>
|
||||
</div>
|
||||
<div class="text-center" data-aos="fade-up" data-aos-delay="300">
|
||||
<i class="fas fa-chart-line fa-3x text-blue-600 mb-4"></i>
|
||||
<h3 class="text-2xl font-semibold mb-2">Scale Operations</h3>
|
||||
<p>Handle large volumes of passports effortlessly.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- FAQ & Contact -->
|
||||
<section id="faq" class="py-20">
|
||||
<div class="container mx-auto px-6 lg:flex lg:space-x-12">
|
||||
<div class="lg:w-1/2" data-aos="fade-right">
|
||||
<h2 class="text-4xl font-bold mb-6">Frequently Asked Questions</h2>
|
||||
<div class="space-y-4">
|
||||
<details class="bg-white p-4 rounded-lg shadow">
|
||||
<summary class="font-semibold cursor-pointer">What passport formats are supported?</summary>
|
||||
<p class="mt-2 text-gray-600">We support passports from multiple countries in various formats.</p>
|
||||
</details>
|
||||
<details class="bg-white p-4 rounded-lg shadow">
|
||||
<summary class="font-semibold cursor-pointer">How accurate is the data extraction?</summary>
|
||||
<p class="mt-2 text-gray-600">Our AI achieves high accuracy rates, minimizing errors in data capture.</p>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
<div class="lg:w-1/2 mt-12 lg:mt-0" data-aos="fade-left">
|
||||
<h2 class="text-4xl font-bold mb-6">Talk to Sales</h2>
|
||||
<form action="https://example.com/contact" method="POST" class="space-y-4">
|
||||
<input type="text" name="name" placeholder="Name*" required class="w-full p-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
<input type="email" name="email" placeholder="Email*" required class="w-full p-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
<input type="tel" name="phone" placeholder="Phone" class="w-full p-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
<textarea name="message" rows="4" placeholder="Message" class="w-full p-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
|
||||
<button type="submit" class="w-full bg-blue-600 text-white font-semibold py-3 rounded-lg hover:bg-blue-700 transition">Submit</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Footer (matched to Invoice page) -->
|
||||
<footer class="bg-gray-800 text-gray-200 py-8">
|
||||
<div class="container mx-auto px-4 text-center">
|
||||
<p class="mb-2">© 2025 AI Infinite. All rights reserved.</p>
|
||||
<p class="mb-2">
|
||||
<a href="#features" class="hover:underline mx-2">Features</a>|
|
||||
<a href="#benefits" class="hover:underline mx-2">Benefits</a>|
|
||||
<a href="#faq" class="hover:underline mx-2">FAQ</a>|
|
||||
<a href="#" class="hover:underline mx-2">Blog</a>|
|
||||
<a href="#" class="hover:underline mx-2">Help Center</a>|
|
||||
<a href="#" class="hover:underline mx-2">API</a>
|
||||
</p>
|
||||
<p class="mb-2">
|
||||
<a href="#" class="hover:underline mx-2">Terms</a>|
|
||||
<a href="#" class="hover:underline mx-2">Privacy Policy</a>|
|
||||
<a href="#" class="hover:underline mx-2">Security</a>|
|
||||
<a href="#" class="hover:underline mx-2">GDPR</a>
|
||||
</p>
|
||||
<p>
|
||||
Follow us:
|
||||
<a href="#" class="mx-2 transform hover:scale-125 transition duration-300"><i class="fab fa-twitter"></i></a>
|
||||
<a href="#" class="mx-2 transform hover:scale-125 transition duration-300"><i class="fab fa-linkedin"></i></a>
|
||||
<a href="#" class="mx-2 transform hover:scale-125 transition duration-300"><i class="fab fa-facebook"></i></a>
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<!-- Scripts -->
|
||||
<script>
|
||||
// Mobile menu toggle
|
||||
document.getElementById('menu-btn').addEventListener('click', () => {
|
||||
document.getElementById('menu').classList.toggle('hidden');
|
||||
});
|
||||
// Navbar shadow on scroll
|
||||
const navbar = document.getElementById('navbar');
|
||||
window.addEventListener('scroll', () => {
|
||||
if (window.scrollY > 50) {
|
||||
navbar.classList.add('shadow-lg');
|
||||
} else {
|
||||
navbar.classList.remove('shadow-lg');
|
||||
}
|
||||
});
|
||||
</script>
|
||||
<!-- AOS JS -->
|
||||
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
|
||||
<script>
|
||||
AOS.init({ duration: 800, once: true });
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,189 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="description" content="AI Infinite Pricing — Choose the plan that fits your needs. Plus, Pro, or Enterprise." />
|
||||
<meta name="keywords" content="AI Infinite, pricing, plans, AI OCR, invoice extraction" />
|
||||
<title>Pricing — AI Infinite</title>
|
||||
<!-- Tailwind CSS CDN -->
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<!-- Font Awesome -->
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
|
||||
<!-- AOS CSS -->
|
||||
<link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
|
||||
<link rel="icon" href="{{ url_for('static', filename='logos/ai infinite.jpg') }}" type="image/x-icon">
|
||||
</head>
|
||||
<body class="antialiased text-gray-800 font-sans">
|
||||
|
||||
<!-- Updated Navbar -->
|
||||
<nav id="navbar" class="fixed top-0 left-0 w-full bg-[#f7f7f7] backdrop-blur shadow-md z-50">
|
||||
<div class="container mx-auto px-6 py-4 flex items-center">
|
||||
<!-- Logo / Brand -->
|
||||
<a href="{{ url_for('home_logged_in') if logged_in else url_for('index') }}" class="flex items-center space-x-2 hover:opacity-90">
|
||||
<img src="{{ url_for('static', filename='logos/aiinfinite.png') }}" alt="AI Infinite Logo" class="h-12 md:h-16 w-auto" />
|
||||
<span class="text-xl font-bold text-gray-800"></span>
|
||||
</a>
|
||||
|
||||
<!-- Combined Right-side Links -->
|
||||
<div class="hidden md:flex items-center ml-auto space-x-12">
|
||||
<a href="{{ url_for('invoice', doc_type='invoice') }}" class="text-gray-700 hover:text-blue-600 font-medium">Invoice</a>
|
||||
<a href="{{ url_for('passport', doc_type='passport') }}" class="text-gray-700 hover:text-blue-600 font-medium">Passport</a>
|
||||
<a href="{{ url_for('pricing') }}" class="text-gray-700 hover:text-blue-600 font-medium">Pricing</a>
|
||||
<a href="{{ url_for('about') }}" class="text-gray-700 hover:text-blue-600 font-medium">About</a>
|
||||
{% if logged_in %}
|
||||
<a href="{{ url_for('dashboard') }}" class="text-gray-700 hover:text-blue-600 font-medium">Dashboard</a>
|
||||
<a href="{{ url_for('logout') }}" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg font-semibold">Logout</a>
|
||||
{% else %}
|
||||
<a href="{{ url_for('login') }}" class="text-gray-700 hover:text-blue-600 font-medium">Log in</a>
|
||||
<a href="{{ url_for('login') }}" class="bg-blue-600 hover:bg-blue-700 text-white px-5 py-2 rounded-lg font-semibold">Get Started</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- Mobile Menu Button -->
|
||||
<button id="menu-btn" class="md:hidden text-gray-700 focus:outline-none">
|
||||
<i class="fas fa-bars fa-2x"></i>
|
||||
</button>
|
||||
</div>
|
||||
<!-- Mobile Menu Content -->
|
||||
<div id="menu" class="hidden md:hidden bg-[#f7f7f7] backdrop-blur shadow-inner">
|
||||
<div class="flex flex-col space-y-2 px-6 py-4">
|
||||
<a href="{{ url_for('invoice', doc_type='invoice') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Invoice</a>
|
||||
<a href="{{ url_for('passport', doc_type='passport') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Passport</a>
|
||||
<a href="{{ url_for('pricing') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Pricing</a>
|
||||
<a href="{{ url_for('about') }}" class="block text-gray-700 hover:text-blue-600 font-medium">About</a>
|
||||
{% if logged_in %}
|
||||
<a href="{{ url_for('dashboard') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Dashboard</a>
|
||||
<a href="{{ url_for('logout') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Logout</a>
|
||||
{% else %}
|
||||
<a href="{{ url_for('login') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Log in</a>
|
||||
<a href="{{ url_for('login') }}" class="block bg-blue-600 hover:bg-blue-700 text-white px-5 py-2 rounded-lg font-semibold text-center">Get Started</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<!-- Hero / Page Title -->
|
||||
<section class="pt-32 pb-12 bg-white text-center">
|
||||
<div class="container mx-auto px-6">
|
||||
<h1 class="text-4xl md:text-5xl font-bold mb-4">Pricing Plans</h1>
|
||||
<p class="text-lg text-gray-600 max-w-2xl mx-auto">Choose the plan that fits your needs. Upgrade or downgrade at any time.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Pricing Cards -->
|
||||
<section id="pricing" class="py-16 bg-gray-50">
|
||||
<div class="container mx-auto px-6">
|
||||
<div class="grid gap-8 md:grid-cols-3">
|
||||
|
||||
<!-- Plus Plan -->
|
||||
<div class="bg-white rounded-xl shadow-lg p-8 flex flex-col" data-aos="fade-up">
|
||||
<h2 class="text-2xl font-semibold mb-4 text-center">Plus</h2>
|
||||
<p class="text-center text-gray-600 mb-6">Ideal for small teams</p>
|
||||
<div class="text-center mb-6">
|
||||
<span class="text-4xl font-bold">$10</span>
|
||||
<span class="text-gray-600">/mo</span>
|
||||
</div>
|
||||
<ul class="space-y-3 mb-6 flex-1">
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> 300 API calls/mo</li>
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> Data Extraction AI</li>
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> API Access</li>
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> Excel & JSON output</li>
|
||||
</ul>
|
||||
<a href="{{ url_for('login') }}" class="mt-auto block bg-blue-600 hover:bg-blue-700 text-white text-center py-3 rounded-lg font-semibold transition">Start Plus</a>
|
||||
</div>
|
||||
|
||||
<!-- Pro Plan -->
|
||||
<div class="bg-white rounded-xl shadow-lg p-8 flex flex-col border-2 border-blue-600" data-aos="fade-up" data-aos-delay="100">
|
||||
<h2 class="text-2xl font-semibold mb-4 text-center">Pro</h2>
|
||||
<p class="text-center text-gray-600 mb-6">For growing businesses</p>
|
||||
<div class="text-center mb-6">
|
||||
<span class="text-4xl font-bold">$25</span>
|
||||
<span class="text-gray-600">/mo</span>
|
||||
</div>
|
||||
<ul class="space-y-3 mb-6 flex-1">
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> 750 API calls/mo</li>
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> Data Extraction AI</li>
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> API Access</li>
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> Excel & JSON output</li>
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> ERP Integration</li>
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> Custom Integration</li>
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> 1:1 Support</li>
|
||||
</ul>
|
||||
<a href="{{ url_for('login') }}" class="mt-auto block bg-blue-600 hover:bg-blue-700 text-white text-center py-3 rounded-lg font-semibold transition">Start Pro</a>
|
||||
</div>
|
||||
|
||||
<!-- Enterprise Plan -->
|
||||
<div class="bg-white rounded-xl shadow-lg p-8 flex flex-col" data-aos="fade-up" data-aos-delay="200">
|
||||
<h2 class="text-2xl font-semibold mb-4 text-center">Enterprise</h2>
|
||||
<p class="text-center text-gray-600 mb-6">Custom solutions at scale</p>
|
||||
<div class="text-center mb-6">
|
||||
<span class="text-4xl font-bold">Custom</span>
|
||||
</div>
|
||||
<ul class="space-y-3 mb-6 flex-1">
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> Unlimited API calls</li>
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> Data Extraction AI</li>
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> API Access</li>
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> Excel & JSON output</li>
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> ERP Integration</li>
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> Custom Integration</li>
|
||||
<li class="flex items-center"><i class="fas fa-check text-blue-600 mr-2"></i> 1:1 Support</li>
|
||||
</ul>
|
||||
<a href="{{ url_for('about') }}" class="mt-auto block bg-gray-800 hover:bg-gray-900 text-white text-center py-3 rounded-lg font-semibold transition">Contact Sales</a>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- FAQ Section -->
|
||||
<section id="faq" class="py-16 bg-white">
|
||||
<div class="container mx-auto px-6 max-w-2xl">
|
||||
<h2 class="text-3xl font-bold text-center mb-8" data-aos="fade-up">Frequently Asked Questions</h2>
|
||||
<div class="space-y-4">
|
||||
<details class="bg-gray-50 p-4 rounded-lg shadow" data-aos="fade-up">
|
||||
<summary class="font-semibold cursor-pointer">Can I switch plans anytime?</summary>
|
||||
<p class="mt-2 text-gray-600">Yes—upgrade or downgrade your plan at any time directly from your dashboard.</p>
|
||||
</details>
|
||||
<details class="bg-gray-50 p-4 rounded-lg shadow" data-aos="fade-up" data-aos-delay="100">
|
||||
<summary class="font-semibold cursor-pointer">Do you offer annual billing?</summary>
|
||||
<p class="mt-2 text-gray-600">Yes—save 20% when you choose annual billing for Plus or Pro plans.</p>
|
||||
</details>
|
||||
<details class="bg-gray-50 p-4 rounded-lg shadow" data-aos="fade-up" data-aos-delay="200">
|
||||
<summary class="font-semibold cursor-pointer">What payment methods are accepted?</summary>
|
||||
<p class="mt-2 text-gray-600">We accept all major credit cards and invoicing for Enterprise customers.</p>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Footer -->
|
||||
<footer class="bg-gray-800 text-gray-200 py-8">
|
||||
<div class="container mx-auto px-6 text-center space-y-4">
|
||||
<img src="{{ url_for('static', filename='logos/aiinfinite.png') }}" class="h-10 mx-auto" alt="AI Infinite">
|
||||
<p>
|
||||
<a href="#" class="hover:underline mx-2">API Docs</a> |
|
||||
<a href="#" class="hover:underline mx-2">Help Center</a> |
|
||||
<a href="#" class="hover:underline mx-2">Blog</a> |
|
||||
<a href="#" class="hover:underline mx-2">Careers</a>
|
||||
</p>
|
||||
<p class="text-sm">+91 82753 67267 | connect@aiindia.ai | Pune, Maharashtra 411009</p>
|
||||
<div class="text-lg">
|
||||
<a href="https://twitter.com/AiIndia2?s=09" class="mx-2 hover:text-white"><i class="fab fa-twitter"></i></a>
|
||||
<a href="https://www.linkedin.com/company/ai-india/" class="mx-2 hover:text-white"><i class="fab fa-linkedin"></i></a>
|
||||
<a href="#" class="mx-2 hover:text-white"><i class="fab fa-medium"></i></a>
|
||||
</div>
|
||||
<p class="text-sm">© 2025 AI Infinite Technologies Inc.</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<!-- Scripts -->
|
||||
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
|
||||
<script>
|
||||
AOS.init({ duration: 800, once: true });
|
||||
document.getElementById('menu-btn').addEventListener('click', () => {
|
||||
document.getElementById('menu').classList.toggle('hidden');
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,50 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Profile Details</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css">
|
||||
<link rel="icon" href="{{ url_for('static', filename='logos/ai infinite.jpg') }}" type="image/x-icon">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="row mt-5">
|
||||
<div class="col-md-6 offset-md-3">
|
||||
<h2 class="text-center">Profile Details</h2>
|
||||
|
||||
<!-- Profile Picture -->
|
||||
<div class="mb-4 text-center">
|
||||
{% if profile_picture %}
|
||||
<img src="{{ url_for('static', filename='profile_pics/' + profile_picture.split('/')[-1]) }}" alt="Profile Picture" class="rounded-circle" width="150" height="150">
|
||||
{% else %}
|
||||
|
||||
</div>
|
||||
|
||||
<!-- User Details -->
|
||||
<table class="table table-bordered">
|
||||
<tbody>
|
||||
<tr>
|
||||
<th>Username</th>
|
||||
<td>{{ username }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Email Address</th>
|
||||
<td>{{ email }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class="text-center mt-4">
|
||||
<a href="{{ url_for('dashboard') }}" class="btn btn-secondary">Back to Dashboard</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,207 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Invoice Extraction Result</title>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
|
||||
<link rel="icon" href="{{ url_for('static', filename='logos/ai infinite.jpg') }}" type="image/x-icon">
|
||||
<style>
|
||||
/* Basic Reset */
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
/* Body Styling */
|
||||
body {
|
||||
font-family: 'Roboto', sans-serif;
|
||||
background-color: #f0f4f8;
|
||||
color: #333;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
/* Main Container */
|
||||
.container {
|
||||
background-color: #fff;
|
||||
padding: 40px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
|
||||
width: 100%;
|
||||
max-width: 900px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* Header Styling */
|
||||
h2 {
|
||||
font-size: 32px;
|
||||
font-weight: 700;
|
||||
margin-bottom: 10px;
|
||||
color: #1a73e8;
|
||||
}
|
||||
|
||||
p.subtitle {
|
||||
font-size: 16px;
|
||||
color: #666;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
/* Invoice Data Display */
|
||||
.invoice-data {
|
||||
background-color: #f8f9fa;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
|
||||
text-align: left;
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
margin-bottom: 20px;
|
||||
border: 1px solid #e0e0e0;
|
||||
}
|
||||
|
||||
pre {
|
||||
font-family: 'Courier New', Courier, monospace;
|
||||
color: #343a40;
|
||||
font-size: 16px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
/* Links */
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #007bff;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* Button Styling */
|
||||
.button-container {
|
||||
margin-top: 20px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 15px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 12px 20px;
|
||||
font-size: 18px;
|
||||
background-color: #1a73e8;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.3s ease;
|
||||
}
|
||||
|
||||
.btn:hover {
|
||||
background-color: #0d47a1;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background-color: #34a853;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background-color: #2e8b45;
|
||||
}
|
||||
|
||||
.btn-copy {
|
||||
background-color: #ff9800;
|
||||
}
|
||||
|
||||
.btn-copy:hover {
|
||||
background-color: #fb8c00;
|
||||
}
|
||||
|
||||
/* File Format Selection */
|
||||
.select-container {
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.file-select {
|
||||
padding: 10px;
|
||||
font-size: 16px;
|
||||
background-color: #f8f9fa;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 5px;
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
/* Animation */
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
.container {
|
||||
animation: fadeIn 0.5s ease-in;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="container">
|
||||
<h2>Invoice Data Extraction Result</h2>
|
||||
<p class="subtitle">Your invoice has been successfully processed. Review the extracted data below.</p>
|
||||
|
||||
<!-- Displaying extracted invoice data -->
|
||||
<div class="invoice-data">
|
||||
<pre id="json-output">{{ json_data }}</pre>
|
||||
</div>
|
||||
|
||||
<!-- File format selection -->
|
||||
<div class="select-container">
|
||||
<label for="file-format" class="font-semibold">Select file format for download:</label><br>
|
||||
<select id="file-format" class="file-select">
|
||||
<option value="json">JSON</option>
|
||||
<option value="excel">Excel</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Button actions -->
|
||||
<div class="button-container">
|
||||
<!-- Back to Upload Page -->
|
||||
<a href="{{ url_for('dashboard') }}" class="btn">Back to Upload</a>
|
||||
|
||||
<!-- Download JSON or Excel -->
|
||||
<form action="{{ url_for('download_file') }}" method="POST" style="display:inline;">
|
||||
<textarea name="json_data" style="display:none;">{{ json_data }}</textarea>
|
||||
<input type="hidden" name="file_format" id="file-format-input">
|
||||
<button type="submit" class="btn btn-secondary">Download File</button>
|
||||
</form>
|
||||
|
||||
<!-- Copy JSON -->
|
||||
<button onclick="copyToClipboard()" class="btn btn-copy">Copy JSON</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Function to copy JSON to clipboard
|
||||
function copyToClipboard() {
|
||||
const jsonOutput = document.getElementById("json-output").innerText;
|
||||
navigator.clipboard.writeText(jsonOutput).then(() => {
|
||||
alert("JSON copied to clipboard!");
|
||||
}).catch(err => {
|
||||
console.error("Failed to copy JSON: ", err);
|
||||
});
|
||||
}
|
||||
|
||||
// Update the file format input before submitting the form
|
||||
document.querySelector("form").onsubmit = function () {
|
||||
const selectedFormat = document.getElementById("file-format").value;
|
||||
document.getElementById("file-format-input").value = selectedFormat;
|
||||
};
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,214 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Login</title>
|
||||
<style>
|
||||
|
||||
body {
|
||||
font-family: 'Arial', sans-serif;
|
||||
/* background-image: linear-gradient(to top, #ebbba7 0%, #cfc7f8 100%); */
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
.container {
|
||||
background-color: #fff;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
|
||||
padding: 30px;
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
h2 {
|
||||
color: #4a4a4a;
|
||||
margin-bottom: 20px;
|
||||
font-size: 2rem;
|
||||
}
|
||||
|
||||
form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
label {
|
||||
font-size: 1rem;
|
||||
color: #333;
|
||||
margin-bottom: 5px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
input[type="text"], input[type="password"] {
|
||||
padding: 12px;
|
||||
font-size: 1rem;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 8px;
|
||||
outline: none;
|
||||
transition: border-color 0.3s ease;
|
||||
}
|
||||
|
||||
input[type="text"]:focus, input[type="password"]:focus {
|
||||
border-color: #5f9ea0;
|
||||
}
|
||||
|
||||
button {
|
||||
background-color: #5f9ea0;
|
||||
color: #fff;
|
||||
font-size: 1rem;
|
||||
padding: 12px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.3s ease;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background-color: #3a7d7d;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #5f9ea0;
|
||||
text-decoration: none;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.links {
|
||||
margin-top: 20px;
|
||||
font-size: 0.9rem;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.links p {
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
/* Flash message container */
|
||||
.message-container {
|
||||
margin-top: 20px;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.message {
|
||||
padding: 10px;
|
||||
margin-bottom: 10px;
|
||||
border-radius: 5px;
|
||||
text-align: center;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #d4edda;
|
||||
color: #155724;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #f8d7da;
|
||||
color: #721c24;
|
||||
}
|
||||
|
||||
.message.info {
|
||||
background-color: #d1e
|
||||
}
|
||||
|
||||
|
||||
login-form {
|
||||
position: relative;
|
||||
animation: slideIn 0.5s ease-in-out;
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
from {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
to {
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Styling the form */
|
||||
form {
|
||||
background-color: #f9f9f9;
|
||||
padding: 20px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
/* Flash message styles */
|
||||
.flash-messages {
|
||||
list-style-type: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.flash-message {
|
||||
padding: 10px;
|
||||
margin: 10px 0;
|
||||
border-radius: 5px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.flash-message.success {
|
||||
background-color: #d4edda;
|
||||
color: #155724;
|
||||
}
|
||||
|
||||
.flash-message.error {
|
||||
background-color: #f8d7da;
|
||||
color: #721c24;
|
||||
}
|
||||
|
||||
.flash-message.warning {
|
||||
background-color: #fff3cd;
|
||||
color: #856404;
|
||||
}
|
||||
|
||||
.flash-message.info {
|
||||
background-color: #cce5ff;
|
||||
color: #004085;
|
||||
}
|
||||
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h2>Login</h2>
|
||||
<form action="{{ url_for('login') }}" method="POST">
|
||||
<label for="username">Username</label>
|
||||
<input type="text" id="username" name="username" required><br>
|
||||
|
||||
<label for="password">Password</label>
|
||||
<input type="password" id="password" name="password" required><br>
|
||||
|
||||
<button type="submit">Login</button>
|
||||
</form>
|
||||
|
||||
<div class="links">
|
||||
<p>Don't have an account? <a href="{{ url_for('signup') }}">Sign up</a></p>
|
||||
<p>Forgot your password? <a href="{{ url_for('forgot_password') }}">Reset Password</a></p>
|
||||
</div>
|
||||
|
||||
{% with messages = get_flashed_messages() %}
|
||||
{% if messages %}
|
||||
<div class="message-container">
|
||||
{% for message in messages %}
|
||||
<div class="message">
|
||||
{{ message }}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,32 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Upload Document - AI Infinite</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css">
|
||||
<style>
|
||||
body { font-family: Arial, sans-serif; background-color: #f8f9fa; }
|
||||
.container { max-width: 800px; margin: 2rem auto; }
|
||||
.card { padding: 1.5rem; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<h5 class="card-title">Upload {{ doc_type|capitalize }} Document</h5>
|
||||
<form action="{{ url_for('upload_image') }}" method="POST" enctype="multipart/form-data">
|
||||
<div class="mb-3">
|
||||
<label for="doc_type" class="form-label">Document Type</label>
|
||||
<input type="text" class="form-control" id="doc_type" name="doc_type" value="{{ doc_type }}" readonly>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="file" class="form-label">Choose File (PDF or Image)</label>
|
||||
<input type="file" class="form-control" id="file" name="file" accept="image/*,application/pdf" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Upload</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,152 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="description" content="Full Invoice Extraction History — AI Infinite" />
|
||||
<meta name="keywords" content="invoice history, AI Infinite, data extraction" />
|
||||
<title>Invoice History — AI Infinite</title>
|
||||
<!-- Tailwind CSS -->
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<!-- Font Awesome -->
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
|
||||
<!-- AOS CSS -->
|
||||
<link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
|
||||
</head>
|
||||
|
||||
<body class="antialiased text-gray-800">
|
||||
|
||||
<!-- Navbar -->
|
||||
<nav id="navbar" class="fixed top-0 left-0 w-full bg-[#f7f7f7] backdrop-blur shadow-md z-50">
|
||||
<div class="container mx-auto px-6 py-4 flex items-center justify-between">
|
||||
<a href="{{ url_for('index') }}" class="flex items-center space-x-2 hover:opacity-90">
|
||||
<img src="{{ url_for('static', filename='logos/aiinfinite.png') }}" alt="AI Infinite Logo"
|
||||
class="h-12 md:h-16 w-auto" />
|
||||
</a>
|
||||
<div class="hidden md:flex space-x-8 items-center">
|
||||
<a href="{{ url_for('invoice', doc_type='invoice') }}"
|
||||
class="text-gray-700 hover:text-blue-600 font-medium">Invoice</a>
|
||||
<a href="{{ url_for('passport', doc_type='passport') }}"
|
||||
class="text-gray-700 hover:text-blue-600 font-medium">Passport</a>
|
||||
<a href="#features" class="text-gray-700 hover:text-blue-600 font-medium">Features</a>
|
||||
<a href="{{ url_for('pricing') }}" class="text-gray-700 hover:text-blue-600 font-medium">Pricing</a>
|
||||
<a href="{{ url_for('about') }}" class="text-gray-700 hover:text-blue-600 font-medium">About</a>
|
||||
</div>
|
||||
<div class="hidden md:flex space-x-4 items-center">
|
||||
{% if logged_in %}
|
||||
<a href="{{ url_for('dashboard') }}" class="text-gray-700 hover:text-blue-600 font-medium">Dashboard</a>
|
||||
<a href="{{ url_for('logout') }}" class="text-gray-700 hover:text-blue-600 font-medium">Logout</a>
|
||||
{% else %}
|
||||
<a href="{{ url_for('login') }}" class="text-gray-700 hover:text-blue-600 font-medium">Log in</a>
|
||||
<a href="{{ url_for('login') }}"
|
||||
class="bg-blue-600 hover:bg-blue-700 text-white px-5 py-2 rounded-lg font-semibold">Get Started</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
<button id="menu-btn" class="md:hidden text-gray-700 focus:outline-none">
|
||||
<i class="fas fa-bars fa-2x"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div id="menu" class="hidden md:hidden bg-[#f7f7f7] backdrop-blur shadow-inner">
|
||||
<div class="flex flex-col space-y-2 px-6 py-4">
|
||||
<a href="{{ url_for('invoice', doc_type='invoice') }}"
|
||||
class="block text-gray-700 hover:text-blue-600 font-medium">Invoice</a>
|
||||
<a href="{{ url_for('passport', doc_type='passport') }}"
|
||||
class="block text-gray-700 hover:text-blue-600 font-medium">Passport</a>
|
||||
<a href="#features" class="block text-gray-700 hover:text-blue-600 font-medium">Features</a>
|
||||
<a href="{{ url_for('pricing') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Pricing</a>
|
||||
<a href="{{ url_for('about') }}" class="block text-gray-700 hover:text-blue-600 font-medium">About</a>
|
||||
{% if logged_in %}
|
||||
<a href="{{ url_for('dashboard') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Dashboard</a>
|
||||
<a href="{{ url_for('logout') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Logout</a>
|
||||
{% else %}
|
||||
<a href="{{ url_for('login') }}" class="block text-gray-700 hover:text-blue-600 font-medium">Log in</a>
|
||||
<a href="{{ url_for('login') }}"
|
||||
class="block bg-blue-600 hover:bg-blue-700 text-white px-5 py-2 rounded-lg font-semibold text-center">Get
|
||||
Started</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<!-- Hero Section -->
|
||||
<section class="pt-32 pb-12 bg-white text-center">
|
||||
<div class="container mx-auto px-6" data-aos="fade-up">
|
||||
<h1 class="text-4xl md:text-5xl font-bold mb-2">Full Extraction History</h1>
|
||||
<p class="text-lg text-gray-600"> <span class="font-semibold">{{ username }}</span></p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- History Table -->
|
||||
<section id="history" class="py-20 bg-gray-50">
|
||||
<div class="container mx-auto px-6" data-aos="fade-up">
|
||||
<div class="overflow-x-auto bg-white rounded-lg shadow">
|
||||
<table class="min-w-full divide-y divide-gray-200">
|
||||
<thead class="bg-gray-50">
|
||||
<tr>
|
||||
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Timestamp</th>
|
||||
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Image Name</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="bg-white divide-y divide-gray-200">
|
||||
{% if invoice_history %}
|
||||
{% for entry in invoice_history %}
|
||||
<tr class="hover:bg-gray-100">
|
||||
<td class="px-6 py-4 whitespace-nowrap text-blue-600 font-semibold">{{ entry.timestamp_str }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('view_invoice', invoice_id=entry.id) }}">
|
||||
{{ entry.image_name }}
|
||||
</a>
|
||||
</td>
|
||||
<!-- <td class="px-6 py-4 whitespace-nowrap">{{ entry.image_name }}</td> -->
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="2" class="px-6 py-4 text-center text-gray-500">No history found.</td>
|
||||
</tr>
|
||||
{% endif %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="text-center mt-8">
|
||||
<a href="{{ url_for('dashboard') }}"
|
||||
class="inline-block bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-6 rounded-lg transition">
|
||||
Back to Dashboard
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Footer -->
|
||||
<footer class="bg-gray-800 text-gray-200 py-8">
|
||||
<div class="container mx-auto px-6 text-center space-y-4">
|
||||
<img src="{{ url_for('static', filename='logos/aiinfinite.png') }}" alt="AI Infinite" class="h-10 mx-auto" />
|
||||
<p>
|
||||
<a href="#" class="hover:underline mx-2">API Docs</a> |
|
||||
<a href="#" class="hover:underline mx-2">Help Center</a> |
|
||||
<a href="#" class="hover:underline mx-2">Blog</a> |
|
||||
<a href="# class=" hover:underline mx-2">Careers</a>
|
||||
</p>
|
||||
<div class="space-x-4 text-lg">
|
||||
<a href="https://twitter.com/AiIndia2?s=09" class="hover:text-white"><i class="fab fa-twitter"></i></a>
|
||||
<a href="https://www.linkedin.com/company/ai-india/" class="hover:text-white"><i
|
||||
class="fab fa-linkedin"></i></a>
|
||||
<a href="#" class="hover:text-white"><i class="fab fa-medium"></i></a>
|
||||
</div>
|
||||
<p class="text-sm">© 2025 AI Infinite Technologies Inc.</p>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<!-- Scripts -->
|
||||
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
|
||||
<script>
|
||||
AOS.init({ duration: 800, once: true });
|
||||
document.getElementById('menu-btn').addEventListener('click', () => {
|
||||
document.getElementById('menu').classList.toggle('hidden');
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,43 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>Extracted Invoice Data</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
background: #f5f5f5;
|
||||
margin: 20px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.json-box {
|
||||
background: #ffffff;
|
||||
color: #000000;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 6px;
|
||||
padding: 15px;
|
||||
max-height: 70vh;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
font-family: Consolas, Monaco, monospace;
|
||||
font-size: 14px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<h2>Extracted Invoice Data</h2>
|
||||
|
||||
<pre class="json-box">
|
||||
{{ invoice_json }}
|
||||
</pre>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
# keep directory
|
||||
Reference in New Issue
Block a user