Files
2026-10-07 17:31:08 +05:30

3189 lines
121 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import item_code_matcher as icm
import sys
if hasattr(sys.stdout, 'reconfigure'):
sys.stdout.reconfigure(encoding='utf-8')
if hasattr(sys.stderr, 'reconfigure'):
sys.stderr.reconfigure(encoding='utf-8')
from dotenv import load_dotenv
load_dotenv()
from gstin_validator import post_process_header_fields
from free_item_splitter import split_free_items, get_free_item_stats
# ================================================================
# ✅ NEW MODULAR HELPERS
# ================================================================
# consistency_checker: WIRED IN near end of extraction — purely additive,
# flags suspicious rows/totals for review without changing any value.
from consistency_checker import run_consistency_checks
# ocr_client: WIRED IN. The old inline QianfanOCRClient class was dead code
# (never instantiated), so importing this instead changes nothing at
# runtime, and removes the duplicate.
from ocr_client import QianfanOCRClient as StandaloneQianfanOCRClient
# pdf_utils: WIRED IN, replacing both inline pdf_to_images_pymupdf()
# definitions. Both live call sites now pass dpi=300 explicitly to
# preserve the exact resolution the old (shadowed) definition used.
from pdf_utils import pdf_to_images as pdf_to_images_standalone, get_pdf_page_count
# seller_gstin_lookup: WIRED IN, replacing the Excel-based
# _apply_seller_master() at the seller-GSTIN-correction call site.
# Uses the hardcoded SELLER_GSTIN_MAP as instructed.
from seller_gstin_lookup import lookup_seller_gstin, apply_seller_gstin_override
# ocr_corrector: WIRED IN below (after seller GSTIN override). app.py had
# ZERO date-correction logic before this — expiry_date/invoice_date/
# due_date/DC_date passed straight through from the model, uncorrected.
# This is what was producing malformed dates like "28-Feb-30". Also
# fixes GSTIN OCR confusion (0/O, 1/I, etc.), HSN codes, and pulls
# Batch/expiry/item_code out of the description text when the fields
# themselves are empty. correct_date()'s own output uses DD/MM/YYYY
# (slashes) — converted to DD-MM-YYYY (hyphens) right after the call,
# in app.py only, so ocr_corrector.py itself stays untouched.
from ocr_corrector import apply_ocr_corrections
# gst_calculator: imported, NOT wired into any call site. This app's real
# GST logic is the Phase A-C pipeline further down (process_gst() is
# defined but deliberately unused — see comment near HEADER_FIELDS),
# which recalculates GST from rate x taxable_value and includes a
# hand-tuned HSN-summary rate backfill for invoices where item rows
# carry no rate (e.g. Kanchan Drugs format). gst_calculator.py instead
# preserves whatever GST amounts were extracted and never recalculates.
# These are opposite philosophies — swapping it in would change tax
# totals on live invoices, so it's left available but inactive pending
# your explicit confirmation.
from gst_calculator import GSTCalculator, enrich_and_validate_gst
import re
import io
import json
import os
from datetime import datetime, timedelta
import unicodedata
import secrets
import time
import bcrypt
import fitz
from flask import (
Flask,
flash,
redirect,
render_template,
request,
jsonify,
send_file,
session,
url_for,
send_from_directory,
)
import base64
import requests as _http_requests
import pandas as pd
from werkzeug.utils import secure_filename
from PIL import Image
import logging
from functools import wraps
from flask_cors import CORS
from werkzeug.security import check_password_hash, generate_password_hash
import ssl
import mysql.connector
from mysql.connector import pooling
from datetime import timedelta
utc_now = datetime.utcnow()
from pdf2image import convert_from_path
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
# ================================================================
# ✅ IMAGE PREPROCESSING (rotation / deskew / contrast / sharpen)
# ================================================================
# Loaded once at module import so the (potentially slow) orientation
# detector isn't re-initialized on every invoice. If preprocessing.py
# or its dependencies (cv2/numpy) aren't available, we fail soft and
# skip preprocessing entirely rather than breaking extraction.
try:
from preprocessing import ImagePreprocessor
_image_preprocessor = ImagePreprocessor()
_PREPROCESSING_ENABLED = True
print("✅ Image preprocessing (orientation/deskew/enhance) loaded.")
except Exception as _prep_err:
_image_preprocessor = None
_PREPROCESSING_ENABLED = False
print(f"⚠️ Image preprocessing unavailable ({_prep_err}). Skipping.")
def preprocess_invoice_image(pil_img):
"""
Run the ImagePreprocessor pipeline (deskew, contrast, sharpen) on a
single page before it's sent to the OCR/vision model.
Orientation correction is intentionally OFF by default. preprocessing.py's
OrientationDetector tries a real OCR-based check first (QianfanOCRClient),
but that module isn't part of this project, so it always fails and silently
falls back to a crude aspect-ratio heuristic ("portrait page => must be
rotated 90/270"). That assumption is wrong for normal A4 invoice pages and
will actively mis-rotate correctly-oriented pages. Re-enable do_orient=True
only once a real orientation signal (working OCR client, or a model-based
check) is wired in.
Denoising is left off too — it tends to blur small print like batch
numbers and GSTINs, which matters more here than general noise.
Falls back to the original image on any failure.
"""
if not _PREPROCESSING_ENABLED:
return pil_img
try:
processed_img, debug_info = _image_preprocessor.process(
pil_img,
do_orient=False,
do_deskew=True,
do_enhance=True,
do_denoise=False,
do_sharpen=True,
)
print(f"🖼️ Preprocessing applied: {debug_info.get('steps_applied')}")
return processed_img
except Exception as e:
print(f"⚠️ Preprocessing failed, using original image: {e}")
return pil_img
# ================================================================
# ✅ UTILITY — normalize unicode to plain ASCII
# ================================================================
def normalize_text(value):
"""Convert unicode characters to closest ASCII. ä→a, é→e, ü→u"""
if not value or not isinstance(value, str):
return value
normalized = unicodedata.normalize("NFKD", value)
return normalized.encode("ascii", "ignore").decode("ascii").strip()
app = Flask(__name__)
from zoneinfo import ZoneInfo
# ================================================================
# ✅ VENDOR MASTER & GSTIN LOOKUP — backed by 'Seller_GSTIN.xlsx'
# ================================================================
from seller_gstin_lookup import load_vendor_master_excel, apply_seller_gstin_override
def _load_seller_master(*args, **kwargs):
"""Backwards-compatible alias for loading vendor master Excel."""
load_vendor_master_excel()
def _apply_seller_master(extracted_data: dict) -> dict:
"""Backwards-compatible alias for applying vendor master and GSTIN override."""
return apply_seller_gstin_override(extracted_data)
# ── OpenRouter / Qwen + Qianfan setup ────────────────────────────────────────
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
QWEN_MODEL = os.getenv("MODEL_NAME", "qwen/qwen3.7-plus")
QIANFAN_MODEL = "baidu/qianfan-ocr-fast:free"
OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1/chat/completions"
# Set USE_QIANFAN=true in .env to use Qianfan OCR model instead of Qwen.
_USE_QIANFAN = os.getenv("USE_QIANFAN", "false").strip().lower() in ("1", "true", "yes")
ACTIVE_MODEL = QIANFAN_MODEL if _USE_QIANFAN else QWEN_MODEL
def _qwen_call(system_prompt: str, user_text: str, image_b64: str,
temperature: float = 0.0, max_tokens: int = 65535) -> str:
"""
Call Qwen vision model via OpenRouter and return the raw response text.
Raises on HTTP error.
"""
headers = {
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
"Content-Type": "application/json",
}
payload = {
"model": ACTIVE_MODEL,
"temperature": temperature,
"max_tokens": max_tokens,
"messages": [
{"role": "system", "content": system_prompt},
{
"role": "user",
"content": [
{"type": "text", "text": user_text},
{"type": "image_url", "image_url": {"url": image_b64}},
],
},
],
}
resp = _http_requests.post(OPENROUTER_BASE_URL, headers=headers, json=payload, timeout=300)
resp.raise_for_status()
data = resp.json()
return data["choices"][0]["message"]["content"].strip()
def _qwen_text_call(system_prompt: str, user_text: str,
temperature: float = 0.0, max_tokens: int = 65535) -> str:
"""Call Qwen text-only (no image) via OpenRouter."""
headers = {
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
"Content-Type": "application/json",
}
payload = {
"model": ACTIVE_MODEL,
"temperature": temperature,
"max_tokens": max_tokens,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_text},
],
}
resp = _http_requests.post(OPENROUTER_BASE_URL, headers=headers, json=payload, timeout=120)
resp.raise_for_status()
data = resp.json()
return data["choices"][0]["message"]["content"].strip()
def _pil_to_b64(pil_img: Image.Image, max_size: int = 2048) -> str:
"""Resize PIL image if needed and return base64 data-URI."""
w, h = pil_img.size
if w > max_size or h > max_size:
scale = max_size / max(w, h)
pil_img = pil_img.resize((int(w * scale), int(h * scale)), Image.Resampling.LANCZOS)
buf = io.BytesIO()
fmt = "JPEG" if w * h > 1_000_000 else "PNG"
pil_img.convert("RGB").save(buf, format=fmt, quality=85 if fmt == "JPEG" else None)
b64 = base64.b64encode(buf.getvalue()).decode()
return f"data:image/{fmt.lower()};base64,{b64}"
# ── Qianfan OCR Client ──────────────────────────────────────────────────
# (moved to ocr_client.py — imported above as StandaloneQianfanOCRClient.
# This inline class was never instantiated anywhere in this file, so
# removing it changes nothing at runtime.)
# Allowed file extensions
ALLOWED_EXTENSIONS = {"pdf", "jpeg", "jpg", "png"}
# API Keys loaded from environment variables
API_KEYS = [os.getenv("API_KEY_1"), os.getenv("API_KEY_2")]
# Usage limit per API key per day
USAGE_LIMIT = 10
# MySQL Configuration
MYSQL_CONFIG = {
"host": os.getenv("MYSQL_HOST"),
"user": os.getenv("MYSQL_USER"),
"password": os.getenv("MYSQL_PASSWORD"),
"database": os.getenv("MYSQL_DB"),
"auth_plugin": "mysql_native_password",
"pool_name": "my_pool",
"pool_size": 20,
"pool_reset_session": True,
"autocommit": True,
"buffered": True,
"connection_timeout": 30,
}
# Connection Pool
try:
cnxpool = mysql.connector.pooling.MySQLConnectionPool(**MYSQL_CONFIG)
except Exception as _e:
print(f"Warning: Failed to initialize MySQL connection pool on startup: {_e}")
cnxpool = None
# print("Sender:", os.getenv("EMAIL_ADDRESS"))
# print("Password:", os.getenv("EMAIL_PASSWORD"))
def format_currency(value, symbol="₹"):
if value is None:
return None
try:
return f"{symbol} {float(value):.2f}"
except:
return value
import sqlite3
class SQLiteCursorWrapper:
def __init__(self, cursor, dictionary=False):
self._cursor = cursor
self.dictionary = dictionary
def execute(self, query, params=None):
query_sql = query.replace('%s', '?')
if params is not None:
if not isinstance(params, (tuple, list, dict)):
params = (params,)
self._cursor.execute(query_sql, params)
else:
self._cursor.execute(query_sql)
return self
def fetchone(self):
row = self._cursor.fetchone()
if row is None:
return None
if self.dictionary and self._cursor.description:
cols = [d[0] for d in self._cursor.description]
return dict(zip(cols, row))
return row
def fetchall(self):
rows = self._cursor.fetchall()
if self.dictionary and self._cursor.description:
cols = [d[0] for d in self._cursor.description]
return [dict(zip(cols, r)) for r in rows]
return rows
@property
def lastrowid(self):
return self._cursor.lastrowid
@property
def rowcount(self):
return self._cursor.rowcount
def close(self):
try:
self._cursor.close()
except Exception:
pass
class SQLiteConnectionWrapper:
def __init__(self, db_path='invoice.db'):
self.conn = sqlite3.connect(db_path, check_same_thread=False)
def cursor(self, dictionary=False, buffered=False):
return SQLiteCursorWrapper(self.conn.cursor(), dictionary=dictionary)
def commit(self):
self.conn.commit()
def rollback(self):
self.conn.rollback()
def close(self):
self.conn.close()
def ping(self, reconnect=True, attempts=1, delay=0):
pass
def start_transaction(self, consistent_snapshot=False, isolation_level=None, readonly=None):
pass
def get_db_connection():
"""Returns a MySQL connection or fallback SQLite connection."""
global cnxpool
try:
if cnxpool is None:
cnxpool = mysql.connector.pooling.MySQLConnectionPool(**MYSQL_CONFIG)
cnx = cnxpool.get_connection()
cnx.ping(reconnect=True, attempts=3, delay=1)
return cnx
except Exception as e:
print(f"MySQL unavailable ({e}). Using SQLite fallback database ('invoice.db').")
return SQLiteConnectionWrapper('invoice.db')
def fix_existing_limits():
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute(
"UPDATE users SET account_limit = 50 WHERE account_limit IS NULL OR account_limit < 50"
)
conn.commit()
cursor.close()
conn.close()
print("User limits updated to 50")
def init_db():
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS contact_queries (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) NOT NULL,
contact VARCHAR(50),
message TEXT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) UNIQUE,
email VARCHAR(255) UNIQUE,
password VARCHAR(255),
phone VARCHAR(20), -- new phone column
invoices_extracted INT DEFAULT 10,
passports_extracted INT DEFAULT 10,
account_limit INT DEFAULT 50,
manual_limit INT DEFAULT 50,
api_limit INT DEFAULT 50,
role VARCHAR(50) DEFAULT 'user'
)
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS extraction_history (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
timestamp DATETIME,
image_name VARCHAR(255),
pages_extracted INT,
extraction_type VARCHAR(50),
input_tokens INT DEFAULT 0,
output_tokens INT DEFAULT 0,
cost_usd DECIMAL(10,6) DEFAULT 0.000000,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
"""
)
# ── Add billing columns to existing table if they don't exist yet ──
for _col, _defn in [
("input_tokens", "INT DEFAULT 0"),
("output_tokens", "INT DEFAULT 0"),
("cost_usd", "DECIMAL(10,6) DEFAULT 0.000000"),
]:
try:
cursor.execute(
f"ALTER TABLE extraction_history ADD COLUMN {_col} {_defn}"
)
except Exception:
pass # Column already exists — ignore
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS api_keys (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
api_key VARCHAR(255) UNIQUE,
created_at DATETIME,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS api_usage (
id INT AUTO_INCREMENT PRIMARY KEY,
api_key VARCHAR(255) UNIQUE,
count INT DEFAULT 0,
last_used DATE,
usage_limit INT,
FOREIGN KEY (api_key) REFERENCES api_keys(api_key) ON DELETE CASCADE
)
"""
)
# ensure admin user exists
cursor.execute(
"SELECT * FROM users WHERE username = 'Niraj' AND email = 'connect.aiindia@gmail.com'"
)
admin_user = cursor.fetchone()
if not admin_user:
cursor.execute(
"""
INSERT INTO users (username, email, password, role)
VALUES (
'Niraj',
'connect.aiindia@gmail.com',
'$2b$12$W9ObhLPinBHdnkX1XK6.U.Ub5mgx33abZtEY7xOVfHz5CMnM5tdWm',
'admin'
)
"""
)
conn.commit()
cursor.close()
conn.close()
# Re-initialize the database
try:
init_db()
except Exception as _db_init_err:
print(f"[Warning] Database initialization skipped on startup: {_db_init_err}")
# Re-initialize the database with the updated schema
# Initialize the Flask app
app = Flask(__name__)
CORS(app)
app.secret_key = os.getenv("FLASK_SECRET_KEY", default="fallback-secret-key")
UPLOAD_FOLDER = "uploads"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
def allowed_file(filename):
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
def check_usage(api_key):
current_date = datetime.now().date()
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
sql = "SELECT * FROM api_usage WHERE api_key = %s"
cursor.execute(sql, (api_key,))
usage_entry = cursor.fetchone()
if not usage_entry:
sql_insert = (
"INSERT INTO api_usage (api_key, count, last_used) VALUES (%s, %s, %s)"
)
cursor.execute(sql_insert, (api_key, 0, current_date))
conn.commit()
usage_entry = {"count": 0, "last_used": current_date, "usage_limit": None}
else:
if usage_entry["last_used"] < current_date:
sql_update = (
"UPDATE api_usage SET count = 0, last_used = %s WHERE api_key = %s"
)
cursor.execute(sql_update, (current_date, api_key))
conn.commit()
usage_entry["count"] = 0
usage_entry["last_used"] = current_date
usage_limit = (
usage_entry["usage_limit"]
if usage_entry["usage_limit"] is not None
else USAGE_LIMIT
)
result = usage_entry["count"] < usage_limit
cursor.close()
conn.close()
return result
def api_key_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
api_key = request.headers.get("X-API-Key")
if not api_key:
return jsonify({"error": "Unauthorized: API Key is required"}), 401
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
sql = "SELECT * FROM api_usage WHERE api_key = %s"
cursor.execute(sql, (api_key,))
key_record = cursor.fetchone()
if not key_record:
cursor.close()
conn.close()
return jsonify({"error": "Unauthorized: Invalid API Key"}), 401
if key_record["count"] >= (
key_record["usage_limit"]
if key_record["usage_limit"] is not None
else USAGE_LIMIT
):
cursor.close()
conn.close()
return jsonify({"error": "Unauthorized: API Key usage limit exceeded"}), 403
sql_update = "UPDATE api_usage SET count = count + 1 WHERE api_key = %s"
cursor.execute(sql_update, (api_key,))
conn.commit()
cursor.close()
conn.close()
return f(*args, **kwargs)
return decorated_function
HEADER_FIELDS = [
"invoice_id",
"invoice_number",
"invoice_date",
"due_date",
"customer_name",
"customer_gstin",
"seller_name",
"seller_gstin",
"currency_code",
"PO_number",
"DC_date",
"DC_number",
"invoice_amount",
"round_off",
"total_gst_rate",
"total_quantity",
"total_cgst_rate",
"total_cgst_amount",
"total_sgst_rate",
"total_sgst_amount",
"total_igst_rate",
"total_igst_amount",
"total_gst_amount"
]
def generate_invoice_id(conn, invoice_source):
prefix = "M" if invoice_source == "manual" else "E"
today = datetime.now().strftime("%Y%m%d")
cursor = conn.cursor()
try:
# ✅ Use SELECT FOR UPDATE — locks the row
# ALL other requests block here until this completes
conn.start_transaction()
cursor.execute(
"""
SELECT last_seq, last_date
FROM invoice_id_lock
WHERE id = 1
FOR UPDATE
"""
)
row = cursor.fetchone()
last_seq = row[0] if row else 0
last_date = row[1] if row else ""
# ✅ Reset sequence if new day
if last_date != today:
new_seq = 1
else:
new_seq = last_seq + 1
# ✅ Update lock table with new sequence
cursor.execute(
"""
UPDATE invoice_id_lock
SET last_seq = %s, last_date = %s
WHERE id = 1
""",
(new_seq, today)
)
conn.commit() # ✅ releases FOR UPDATE lock
invoice_id = f"{prefix}{today}{str(new_seq).zfill(3)}"
print(f"✅ Generated invoice_id: {invoice_id}")
return invoice_id
except Exception as e:
conn.rollback()
print(f"❌ Invoice ID error: {e}")
# Fallback
import random
return f"{prefix}{today}{str(random.randint(100,999))}"
finally:
cursor.close()
def extract_invoice_fields(file_path, invoice_source="electronic", is_dmh=False):
conn = None
try:
filename = os.path.basename(file_path)
print(f"\n{'='*70}", flush=True)
print(f"🚀 [EXTRACTION START] File: {filename} | Mode: {invoice_source} | Role: {'DMH' if is_dmh else 'Standard'}", flush=True)
print(f"{'='*70}", flush=True)
# ===============================
# 🔥 STEP 1: CREATE DB CONNECT
# ===============================
conn = get_db_connection()
# ===============================
# 🔥 STEP 2: GENERATE invoice_id
# ===============================
invoice_id = generate_invoice_id(conn, invoice_source)
# ===============================
# 🔹 STEP 3: Convert PDF to images
# ===============================
file_ext = os.path.splitext(file_path)[1].lower()
if file_ext == ".pdf":
images = pdf_to_images_standalone(file_path, dpi=300)
else:
images = [Image.open(file_path)]
print(f"📄 Loaded document: {len(images)} page(s) detected", flush=True)
# ── Preprocess every page before OCR (orientation, deskew, contrast, sharpen) ──
images = [preprocess_invoice_image(img) for img in images]
# ── Extract page text for multi-page alignment / fallback ──
page_texts = []
if file_ext == ".pdf":
try:
_doc = fitz.open(file_path)
for _p in _doc:
page_texts.append(_p.get_text() or "")
_doc.close()
except Exception as _fitz_err:
print(f"⚠️ Could not extract text via fitz: {_fitz_err}", flush=True)
import uuid
all_pages_data = []
# ── Billing accumulators (across all pages of this invoice) ──────
_total_input_tokens = 0
_total_output_tokens = 0
# Qwen2.5-VL-72B on OpenRouter pricing (USD per token) — update if rates change
_INPUT_PRICE_PER_TOKEN = 0.40 / 1_000_000
_OUTPUT_PRICE_PER_TOKEN = 1.20 / 1_000_000
from schema import SYSTEM_PROMPT, USER_PROMPT
for pg_idx, img in enumerate(images):
# Convert PIL Image → base64 data-URI for OpenRouter
image_b64 = _pil_to_b64(img)
# Context injection for multi-page invoices:
user_prompt_page = USER_PROMPT
if pg_idx > 0 and all_pages_data:
prev_items = [
it for it in (all_pages_data[-1].get("items") or all_pages_data[-1].get("Items") or [])
if it.get("description") and str(it.get("description")).strip() not in ('?', 'null', 'none', 'N/A', '')
]
if prev_items:
last_it = prev_items[-1]
if not last_it.get("Batch") or not last_it.get("expiry_date"):
prev_desc = str(last_it.get("description", ""))[:40]
user_prompt_page += (
f"\n\n⚠️⚠️⚠️ CRITICAL PAGE CONTINUATION:\n"
f"The PREVIOUS page ended with item '{prev_desc}' which has NO batch or expiry date extracted yet.\n"
f"LOOK AT THE TOP OF THIS PAGE:\n"
f"If this page starts with 'Batch & Expiry' or 'Item Code' lines before the next numbered product,\n"
f"those lines belong to '{prev_desc}' from the previous page!\n"
f"Return them as: {{'_continuation_for_previous_page': True, 'Batch': '...', 'expiry_date': '...', 'item_code': '...'}}\n"
f"DO NOT attach them to the first product on this page!\n"
)
# Call Qwen vision model via OpenRouter
print(f"🌐 Sending page {pg_idx + 1} to {ACTIVE_MODEL} via OpenRouter...")
response_text = _qwen_call(
system_prompt=SYSTEM_PROMPT,
user_text=user_prompt_page,
image_b64=image_b64,
temperature=0.0,
max_tokens=65535,
)
# ── Token usage is not returned by OpenRouter for Qwen —
# keep accumulators at zero (billing section still runs cleanly)
_in, _out = 0, 0
_total_input_tokens += _in
_total_output_tokens += _out
print(f"📊 Page processed — tokens not reported by OpenRouter")
# ── Clean common Gemini JSON artefacts ──────────────────────
# 1. Strip markdown fences (```json ... ``` or ``` ... ```)
if response_text.startswith("```"):
response_text = response_text.strip("`")
if response_text.lower().startswith("json"):
response_text = response_text[4:]
response_text = response_text.strip()
# 2. Remove trailing asterisks that appear in amount cells
# e.g. "15393.60*" → "15393.60"
import re as _re
response_text = _re.sub(r'(\d)\*+', r'\1', response_text)
# 3. Trim to last closing brace (handles trailing garbage)
if "}" in response_text:
response_text = response_text[: response_text.rfind("}") + 1]
# 3b. Strip trailing commas before ] or } — the #1 cause of
# "Expecting value" JSONDecodeError in LLM-generated JSON,
# e.g. `{"a": 1},\n]` → `{"a": 1}\n]`
response_text = _re.sub(r',(\s*[\]}])', r'\1', response_text)
# ── Attempt JSON parse with one auto-repair retry ────────────
def _try_parse(text):
"""Try json.loads; on failure attempt basic repairs."""
try:
return json.loads(text), None
except json.JSONDecodeError as e:
return None, e
def _repair_json(text):
"""
Close any unterminated strings/arrays/objects so that
json.loads has a better chance of succeeding.
Handles the most common Gemini truncation patterns.
"""
# Remove all control chars except tab/newline
text = _re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', text)
# Replace smart/curly quotes with straight quotes
text = text.replace('\u201c', '"').replace('\u201d', '"')
text = text.replace('\u2018', "'").replace('\u2019', "'")
# Close any unterminated string: find last unescaped quote
# by counting depth. Simple heuristic: if odd number of
# unescaped double-quotes after the last complete value,
# append a closing quote.
try:
json.loads(text)
return text # already valid
except json.JSONDecodeError as e:
msg = str(e)
if "Unterminated string" in msg or "Invalid control character" in msg:
# Truncate at the position of the error
pos = e.pos
text = text[:pos].rstrip().rstrip(',')
# If we're inside an unterminated string, close it first
# Count unescaped double-quotes: odd count → still inside string
unescaped_quotes = len(_re.findall(r'(?<!\\\\)"', text))
if unescaped_quotes % 2 == 1:
text += '"' # close the open string
text = text.rstrip().rstrip(',')
# Close open structures
open_braces = text.count('{') - text.count('}')
open_brackets = text.count('[') - text.count(']')
text += ']' * max(open_brackets, 0)
text += '}' * max(open_braces, 0)
return text
page_data, err = _try_parse(response_text)
if page_data is None:
print(f"JSON parsing error (attempt 1): {err}")
repaired = _repair_json(response_text)
page_data, err2 = _try_parse(repaired)
if page_data is None:
print(f"JSON parsing error (attempt 2 after repair): {err2}")
# Last resort: retry Qwen with an explicit JSON-only instruction
try:
retry_prompt = (
"The following text is a broken JSON invoice extraction. "
"Fix it and return ONLY valid JSON, nothing else:\n\n"
+ response_text[:3000]
)
retry_text = _qwen_text_call(
system_prompt="You are a JSON repair engine. Return ONLY valid JSON.",
user_text=retry_prompt,
temperature=0.0,
max_tokens=65535,
)
retry_text = retry_text.strip().strip("`").strip()
if retry_text.lower().startswith("json"):
retry_text = retry_text[4:].strip()
if "}" in retry_text:
retry_text = retry_text[: retry_text.rfind("}") + 1]
page_data, err3 = _try_parse(retry_text)
if page_data is None:
print(f"JSON parsing error (attempt 3 Qwen retry): {err3}")
page_data = {"error": "Invalid JSON after all repair attempts"}
else:
print("✅ JSON recovered via Qwen retry")
except Exception as retry_exc:
print(f"Qwen retry failed: {retry_exc}")
page_data = {"error": "Invalid JSON returned from Qwen"}
else:
print("✅ JSON recovered via local repair")
all_pages_data.append(page_data)
if isinstance(page_data, dict):
items_cnt = len(page_data.get("items") or page_data.get("Items") or [])
inv_no = page_data.get("invoice_number") or "N/A"
po_no = page_data.get("PO_number") or "N/A"
amt = page_data.get("invoice_amount") or "N/A"
print(f"📦 [PAGE {pg_idx + 1}/{len(images)}] Extracted {items_cnt} item(s) | Inv#: {inv_no} | PO#: {po_no} | Amount: {amt}", flush=True)
# ---------------------------------------------------------------
# 🔥 PO NUMBER RAW-TEXT FALLBACK
#
# If JSON parsing was truncated/repaired, PO_number may be
# missing from page_data even though it exists in the raw
# response or in the original PDF text. As a safety net,
# scan response_text directly with regex patterns that match
# known PO/Order number formats before the DMH gate runs.
# ---------------------------------------------------------------
if isinstance(page_data, dict) and not page_data.get("PO_number"):
_po_patterns = [
r'(?:Order\s*No\.?|P\.?O\.?\s*No\.?|PO\s*No\.?|'
r'Purchase\s*Order\s*No\.?|Remark\s*:?)\s*[:\-]?\s*'
r'([A-Za-z0-9][A-Za-z0-9/\-]{4,})',
r'(DMH/PO/[A-Za-z0-9/\-]+)',
r'(DMH/[A-Za-z0-9/\-]+)',
]
for _pat in _po_patterns:
_m = _re.search(_pat, response_text, _re.IGNORECASE)
if _m:
_po_candidate = _m.group(1).strip().rstrip('.')
page_data["PO_number"] = _po_candidate
print(f"📌 PO extracted from raw text: {_po_candidate!r}", flush=True)
break
cgst_rates, sgst_rates, igst_rates = set(), set(), set()
# ===============================================================
# 🔥 FEATURE 1 — Deduplicate replica pages (Original / Duplicate / Triplicate)
#
# Invoices in PDFs frequently contain 2 or more pages where Page 2
# is an identical replica copy (e.g. "Duplicate for Transporter",
# "Triplicate", or duplicate buyer copy).
#
# When both pages represent the same invoice and all items on Page 2
# are identical to Page 1 (no new items):
# → SKIP the replica page so only 1 page's output is shown in the JSON!
# When Page 2 has new/different items:
# → It is a CONTINUATION page, so KEEP both pages!
# ===============================================================
_invoice_cost = (
_total_input_tokens * _INPUT_PRICE_PER_TOKEN +
_total_output_tokens * _OUTPUT_PRICE_PER_TOKEN
)
print(f"💰 Invoice total — input: {_total_input_tokens}, "
f"output: {_total_output_tokens}, cost: ${_invoice_cost:.6f}", flush=True)
def _norm_str(s):
if not s:
return ""
return str(s).strip().upper()
def _normalise_po(val):
if not val:
return ""
s = str(val).strip().upper()
if s in ("NONE", "NULL", "N/A", "NA", "-", "NOT FOUND", "EMPTY", "UNDEFINED"):
return ""
return s
def _clean_desc_text(d):
text = str(d or '').lower()
text = re.sub(r'(?:catalog|cat|ref|item|part)\s*(?:no|number)?\s*[:\-]?\s*[a-z0-9]+', '', text)
return re.sub(r'[^a-z0-9]', '', text)
def _items_match(it_a, it_b):
code_a = _norm_str(it_a.get("item_code"))
code_b = _norm_str(it_b.get("item_code"))
batch_a = _norm_str(it_a.get("Batch"))
batch_b = _norm_str(it_b.get("Batch"))
qty_a = str(it_a.get("quantity") or "").strip()
qty_b = str(it_b.get("quantity") or "").strip()
price_a = str(it_a.get("unit_price") or "").strip()
price_b = str(it_b.get("unit_price") or "").strip()
total_a = str(it_a.get("total_price") or it_a.get("taxable_value") or "").strip()
total_b = str(it_b.get("total_price") or it_b.get("taxable_value") or "").strip()
# Rule 1: Same item_code AND same batch
if code_a and code_b and code_a == code_b and batch_a and batch_b and batch_a == batch_b:
return True
# Rule 2: Same batch AND (same quantity OR same price)
if batch_a and batch_b and batch_a == batch_b and (qty_a == qty_b or price_a == price_b):
return True
# Rule 3: Same item_code AND (same quantity OR same price OR same total)
if code_a and code_b and code_a == code_b and (qty_a == qty_b or price_a == price_b or total_a == total_b):
return True
# Rule 4: Clean description match AND (same batch OR same quantity OR same price)
desc_a = _clean_desc_text(it_a.get("description"))
desc_b = _clean_desc_text(it_b.get("description"))
if desc_a and desc_b and (desc_a == desc_b or desc_a in desc_b or desc_b in desc_a):
if (batch_a and batch_b and batch_a == batch_b) or (qty_a and qty_b and qty_a == qty_b) or (price_a and price_b and price_a == price_b):
return True
return False
def _get_page_items(p):
return p.get("items") or p.get("Items") or []
def _is_page_replica_of(page_curr, page_prev):
curr_items = _get_page_items(page_curr)
prev_items = _get_page_items(page_prev)
if not curr_items or not prev_items:
return False, 0
# Count how many items on curr page match an item on prev page
matched = 0
for it_curr in curr_items:
for it_prev in prev_items:
if _items_match(it_prev, it_curr):
matched += 1
break
inv_curr = _norm_str(page_curr.get("invoice_number"))
inv_prev = _norm_str(page_prev.get("invoice_number"))
same_invoice_no = bool(inv_curr and inv_prev and inv_curr == inv_prev)
po_curr = _norm_str(page_curr.get("PO_number"))
po_prev = _norm_str(page_prev.get("PO_number"))
same_po = bool(po_curr and po_prev and po_curr == po_prev)
amt_curr = str(page_curr.get("invoice_amount") or "").strip()
amt_prev = str(page_prev.get("invoice_amount") or "").strip()
same_amount = bool(amt_curr and amt_prev and amt_curr == amt_prev and amt_curr not in ("0", "0.0", "0.00", ""))
# Decision criteria for duplicate invoice:
# 1. 100% of items on curr page match prev page
if matched > 0 and matched == len(curr_items):
return True, matched
# 2. Same invoice number (or same PO & amount) and at least 60% of items match
if (same_invoice_no or (same_po and same_amount)) and matched >= 2 and (matched >= len(curr_items) * 0.6):
return True, matched
# 3. Same invoice number, same total amount, and same item count
if same_invoice_no and same_amount and len(curr_items) == len(prev_items) and matched > 0:
return True, matched
return False, matched
if len(all_pages_data) > 1:
print(f"🔁 Checking multi-page deduplication across {len(all_pages_data)} pages...", flush=True)
deduplicated_pages = [all_pages_data[0]]
for p_idx in range(1, len(all_pages_data)):
page = all_pages_data[p_idx]
curr_items = _get_page_items(page)
# If page has NO items, it might be a tax summary or footer page — keep it
if not curr_items:
deduplicated_pages.append(page)
continue
# Check if this page is a duplicate copy of any previously kept page
is_replica = False
for prev_idx, prev_page in enumerate(deduplicated_pages):
is_rep, matched_cnt = _is_page_replica_of(page, prev_page)
if is_rep:
is_replica = True
inv_display = page.get("invoice_number") or prev_page.get("invoice_number") or "N/A"
print(f"🔁 Duplicate invoice copy detected: Page {p_idx+1} is a duplicate copy of Page {prev_idx+1} "
f"(Invoice: {inv_display!r}, {matched_cnt}/{len(curr_items)} items matched). Extracting only 1 invoice copy.", flush=True)
# Backfill any missing fields from duplicate page into previous page
for fld in HEADER_FIELDS:
if not prev_page.get(fld) and page.get(fld):
prev_page[fld] = page[fld]
break
if not is_replica:
print(f"📄 Continuation page kept: Page {p_idx+1} ({len(curr_items)} items found).", flush=True)
deduplicated_pages.append(page)
all_pages_data = deduplicated_pages
# ===============================================================
# 🔥 FEATURE 2 — PO number required gate (DMH ONLY)
#
# After deduplication, check whether at least one page carries a
# non-empty PO number. If not, reject the whole invoice and
# return a clear error — do NOT proceed with extraction.
#
# This logic runs ONLY for DMH users (is_dmh=True).
# Regular users are not affected and their invoices are processed
# regardless of whether a PO number is present.
# ===============================================================
if is_dmh:
print("📋 [DMH] Validating PO number requirement...", flush=True)
invoice_po = None
for page in all_pages_data:
po = _normalise_po(page.get("PO_number"))
if po:
invoice_po = po
break
# If still missing, check document text extracted by fitz (PDF)
if not invoice_po and 'page_texts' in locals() and page_texts:
for pt in page_texts:
for pat in [
r'(?:Order\s*No\.?|P\.?O\.?\s*No\.?|PO\s*No\.?|Purchase\s*Order\s*No\.?|Remark\s*:?)\s*[:\-]?\s*([A-Za-z0-9][A-Za-z0-9/\-]{4,})',
r'(DMH/PO/[A-Za-z0-9/\-]+)',
r'(DMH/[A-Za-z0-9/\-]+)',
]:
m = _re.search(pat, pt, _re.IGNORECASE)
if m:
cand = _normalise_po(m.group(1))
if cand:
invoice_po = cand
print(f"📌 [DMH] Recovered PO from document raw text: {invoice_po}", flush=True)
for p in all_pages_data:
if not p.get("PO_number"):
p["PO_number"] = invoice_po
break
if invoice_po:
break
if not invoice_po:
print("❌ [DMH] Invoice rejected — no PO number found on document.", flush=True)
return {
"error": "Invoice rejected: PO number is missing. Only invoices with a valid PO number are processed for DMH."
}
print(f"✅ [DMH] PO number confirmed: {invoice_po}", flush=True)
# ===============================================================
print("🔍 ALL PAGES DATA:", all_pages_data)
if all_pages_data:
print("🔍 FIRST PAGE KEYS:", all_pages_data[0].keys())
print("🔍 ITEMS:", all_pages_data[0].get("items"))
# ===================================================
# 🔥 ADD COMPLETE GST PROCESSING CODE RIGHT HERE
# ===================================================
from decimal import Decimal, ROUND_HALF_UP
def round2(value):
return float(
Decimal(str(value)).quantize(
Decimal("0.01"),
rounding=ROUND_HALF_UP
)
)
def safe_float(value):
if value is None:
return 0.0
try:
# Strip everything except digits, dot, minus
cleaned = re.sub(r"[^\d.\-]", "", str(value).strip())
return float(cleaned) if cleaned else 0.0
except:
return 0.0
def process_gst(all_pages_data, final_header):
final_header["total_cgst_amount"] = 0
final_header["total_sgst_amount"] = 0
final_header["total_igst_amount"] = 0
final_header["total_gst_amount"] = 0
total_cgst_amount = 0
total_sgst_amount = 0
total_igst_amount = 0
cgst_rates = set()
sgst_rates = set()
igst_rates = set()
for page in all_pages_data:
# 🔥 Handle both "items" and "Items"
items = page.get("items") or page.get("Items") or []
for item in items:
print("DEBUG qty:", repr(item.get("quantity")),
"unit_price:", repr(item.get("unit_price")),
"Value:", repr(item.get("Value")),
"cgst_rate:", repr(item.get("cgst_rate")))
qty = safe_float(item.get("quantity"))
unit_price = safe_float(item.get("unit_price"))
total_price = safe_float(item.get("total_price"))
discount = safe_float(item.get("Discount"))
value_field = safe_float(item.get("Value"))
# ✅ PRIORITY 1: If Value field exists, use it (most correct)
if value_field > 0:
taxable = round2(value_field)
# ✅ PRIORITY 2: If discount exists, calculate manually
elif discount > 0:
gross = qty * unit_price
taxable = round2(gross - (gross * discount / 100))
# ✅ PRIORITY 3: Use total_price
elif total_price > 0:
taxable = round2(total_price)
# ✅ FINAL fallback
else:
taxable = round2(qty * unit_price)
item["taxable_value"] = taxable
cgst_rate = safe_float(item.get("cgst_rate")) # ✅ handles None
sgst_rate = safe_float(item.get("sgst_rate")) # ✅ handles None
igst_rate = safe_float(item.get("igst_rate"))
# ✅ Always recalculate (do NOT depend on Gemini amount)
item["cgst_amount"] = round2(taxable * cgst_rate / 100)
item["sgst_amount"] = round2(taxable * sgst_rate / 100)
item["igst_amount"] = round2(taxable * igst_rate / 100)
#ADD THESE TWO LINES
item["GST_AMT"] = round2(item["cgst_amount"] + item["sgst_amount"] + item["igst_amount"])
item["Gst%"] = round2(cgst_rate + sgst_rate + igst_rate)
total_cgst_amount += item["cgst_amount"]
total_sgst_amount += item["sgst_amount"]
total_igst_amount += item["igst_amount"]
if cgst_rate > 0:
cgst_rates.add(cgst_rate)
if sgst_rate > 0:
sgst_rates.add(sgst_rate)
if igst_rate > 0:
igst_rates.add(igst_rate)
# 🔥 Normalize items key
page["items"] = items
final_header["total_cgst_amount"] = round2(total_cgst_amount)
final_header["total_sgst_amount"] = round2(total_sgst_amount)
final_header["total_igst_amount"] = round2(total_igst_amount)
final_header["total_gst_amount"] = round2(
total_cgst_amount + total_sgst_amount + total_igst_amount
)
if len(cgst_rates) == 1:
final_header["total_cgst_rate"] = list(cgst_rates)[0]
if len(sgst_rates) == 1:
final_header["total_sgst_rate"] = list(sgst_rates)[0]
if len(igst_rates) == 1:
final_header["total_igst_rate"] = list(igst_rates)[0]
# TOTAL GST RATE
if final_header.get("total_igst_rate"):
final_header["total_gst_rate"] = final_header["total_igst_rate"]
elif final_header.get("total_cgst_rate") and final_header.get("total_sgst_rate"):
final_header["total_gst_rate"] = round2(
final_header["total_cgst_rate"] +
final_header["total_sgst_rate"]
)
return all_pages_data, final_header
print("🔍 ALL PAGES DATA:", all_pages_data)
# ===============================
# BUILD FINAL HEADER
# ===============================
final_header = {field: None for field in HEADER_FIELDS}
for page in all_pages_data:
for field in HEADER_FIELDS:
value = page.get(field)
if isinstance(value, dict):
value = value.get("value")
if final_header[field] in (None, "", 0) and value not in (None, "", 0):
final_header[field] = value
# process_gst() call intentionally removed:
# Phases A-C below handle dedup + rate backfill + GST recalculation
# in the correct order. Calling process_gst() here would overwrite
# cgst_rate/sgst_rate with 0.0 (via safe_float(None)) BEFORE the
# HSN rate lookup has a chance to backfill them, causing all GST
# amounts to be incorrectly zeroed out on invoices where Gemini
# returns cgst_rate: null on item rows (rates only in HSN summary).
# ===============================================================
# ===============================================================
# STEP 5: BUILD FINAL OUTPUT
# ===============================================================
# ---------------------------------------------------------------
# 🔥 PHASE A — Build HSN → rate lookup from ALL pages
#
# On some invoice formats (e.g. Kanchan Drugs), the item rows on
# page 1 carry cgst_rate: null because the rate column is absent
# from the item table. The CGST/SGST rates only appear in the
# HSN summary table printed on page 2.
#
# We scan every page's items for non-null rates and build a
# lookup keyed by (hsn_sac, taxable_value). If that is too
# sparse we also keep a simpler hsn_sac → rate map.
# ---------------------------------------------------------------
hsn_rate_lookup = {} # hsn_sac (str) → {"cgst": float, "sgst": float, "igst": float}
taxable_rate_lookup = {} # (hsn_sac, taxable_value_str) → rates (more precise)
for page in all_pages_data:
for item in (page.get("items") or page.get("Items") or []):
hsn = str(item.get("hsn_sac") or "").strip()
cr = item.get("cgst_rate")
sr = item.get("sgst_rate")
ir = item.get("igst_rate")
if not hsn:
continue
# Only record if at least one rate is non-null and non-zero
cr_v = safe_float(cr)
sr_v = safe_float(sr)
ir_v = safe_float(ir)
if cr_v > 0 or sr_v > 0 or ir_v > 0:
rates = {"cgst": cr_v, "sgst": sr_v, "igst": ir_v}
hsn_rate_lookup[hsn] = rates
tv = str(safe_float(item.get("taxable_value") or item.get("total_price") or 0))
taxable_rate_lookup[(hsn, tv)] = rates
# ---------------------------------------------------------------
# 🔥 PHASE B — Item-level deduplication
#
# PDFs often contain multiple invoice copies (Original, Duplicate,
# Triplicate). Strategy: collect items in order; skip any item that is
# an exact clone of an already seen item (same item_code/batch/qty/price).
# Multiple DIFFERENT items sharing the same item_code (different batch,
# different qty, or different description) are ALWAYS preserved!
# ---------------------------------------------------------------
def _get_item_unique_key(item, fallback_idx):
code = str(item.get("item_code") or "").strip().lower()
batch = str(item.get("Batch") or "").strip().lower()
qty = str(item.get("quantity") or "").strip()
price = str(item.get("unit_price") or "").strip()
total = str(item.get("total_price") or item.get("taxable_value") or "").strip()
is_free = str(item.get("free_item_yn") or item.get("free_item") or "0")
# Clean desc without catalog numbers for matching
clean_d = re.sub(r'(?:catalog|cat|ref|item|part)\s*(?:no|number)?\s*[:\-]?\s*[a-z0-9]+', '', str(item.get("description") or "").lower())
clean_d = re.sub(r'[^a-z0-9]', '', clean_d)
# If it's an empty ghost row
if not clean_d and not batch and not code:
return f"__ghost_{fallback_idx}__"
# Composite key for item identity:
if code and batch:
return f"cb_{code}_{batch}_{qty}_{price}_{is_free}"
elif code and qty:
return f"cq_{code}_{clean_d}_{qty}_{price}_{is_free}"
elif batch and qty:
return f"bq_{batch}_{clean_d}_{qty}_{price}_{is_free}"
elif clean_d and qty:
return f"dq_{clean_d}_{qty}_{price}_{is_free}"
else:
return f"__raw_{clean_d}_{qty}_{price}_{fallback_idx}__"
# ── Cross-page continuation merge ──
for p_idx in range(1, len(all_pages_data)):
curr_items = all_pages_data[p_idx].get("items") or all_pages_data[p_idx].get("Items") or []
prev_items = all_pages_data[p_idx - 1].get("items") or all_pages_data[p_idx - 1].get("Items") or []
if not curr_items or not prev_items:
continue
first_curr = curr_items[0]
is_cont = first_curr.get("_continuation_for_previous_page") or (
not str(first_curr.get("description") or "").strip() and (
first_curr.get("Batch") or first_curr.get("expiry_date") or first_curr.get("item_code")
)
)
if is_cont:
last_prev = prev_items[-1]
for fld in ("Batch", "expiry_date", "item_code", "hsn_sac", "Pack", "MRP"):
if first_curr.get(fld) and not last_prev.get(fld):
last_prev[fld] = first_curr[fld]
desc_prev = str(last_prev.get('description', ''))[:35]
print(f" [CONTINUATION] Merged page {p_idx+1} header into {desc_prev}", flush=True)
curr_items.pop(0)
raw_items = [
item
for page in all_pages_data
for item in (page.get("items") or page.get("Items") or [])
]
seen_item_keys = set()
deduped_items = []
for idx, item in enumerate(raw_items):
key = _get_item_unique_key(item, idx)
is_free = (item.get("free_item") == 1 or str(item.get("free_item_yn")) == "1")
# Skip duplicate replica item from duplicate pages
if key and not key.startswith("__ghost_") and not key.startswith("__raw_") and not is_free:
if key in seen_item_keys:
desc_preview = item.get("description") or item.get("Batch") or "?"
print(f"🔁 Duplicate replica item skipped: {desc_preview!r} (code={item.get('item_code')}, batch={item.get('Batch')})", flush=True)
continue
seen_item_keys.add(key)
elif key and not key.startswith("__ghost_"):
seen_item_keys.add(key)
deduped_items.append(item)
# ---------------------------------------------------------------
# 🔥 GHOST ITEM FILTER — safety net after deduplication
#
# A ghost row is produced when Gemini sees a page-continuation
# line (batch/item_code only, no description/qty/price) and
# mistakenly creates a new item object for it.
# Drop any item where description, quantity, unit_price AND
# total_price are ALL null/zero/empty.
# ---------------------------------------------------------------
def _is_ghost(item):
desc = item.get("description")
qty = item.get("quantity")
unit_price = item.get("unit_price")
total_price = item.get("total_price")
def _empty(v):
if v is None: return True
if isinstance(v, str) and v.strip() == "": return True
try: return float(v) == 0.0
except: return False
return _empty(desc) and _empty(qty) and _empty(unit_price) and _empty(total_price)
clean_items = []
for item in deduped_items:
if _is_ghost(item):
b = item.get("Batch") or item.get("item_code") or "unknown"
print(f"\U0001f47b Ghost item removed: Batch/Code={b!r}")
else:
clean_items.append(item)
deduped_items = clean_items
# ---------------------------------------------------------------
# 🔥 PHASE C — Backfill null rates using HSN lookup, then
# recalculate GST amounts for every deduplicated item
# ---------------------------------------------------------------
total_cgst_amount = 0.0
total_sgst_amount = 0.0
total_igst_amount = 0.0
cgst_rates_seen = set()
sgst_rates_seen = set()
igst_rates_seen = set()
total_taxable = 0.0
for item in deduped_items:
# --- backfill rates if missing ---
cr = item.get("cgst_rate")
sr = item.get("sgst_rate")
ir = item.get("igst_rate")
cr_v = safe_float(cr)
sr_v = safe_float(sr)
ir_v = safe_float(ir)
if cr_v == 0.0 and sr_v == 0.0 and ir_v == 0.0:
hsn = str(item.get("hsn_sac") or "").strip()
tv = str(safe_float(item.get("taxable_value") or item.get("total_price") or 0))
# Priority 1: precise HSN+taxable lookup built from other pages
fallback = taxable_rate_lookup.get((hsn, tv)) or hsn_rate_lookup.get(hsn)
# Priority 2: split Gst% field (Gemini extracts the GST% column value here)
# For intra-state invoices (CGST+SGST), Gst% = CGST% + SGST%, so each = Gst%/2
# For inter-state invoices (IGST only), igst_rate = Gst%
if not fallback:
gst_pct = safe_float(item.get("Gst%"))
if gst_pct > 0:
# Determine if inter-state (IGST) or intra-state (CGST+SGST)
# Use invoice-level clue: if any page has igst_amount > 0 at header level
# or if total_igst_amount > 0 in final_header, it is inter-state
is_igst = safe_float(final_header.get("total_igst_amount")) > 0
if is_igst:
fallback = {"cgst": 0.0, "sgst": 0.0, "igst": gst_pct}
else:
half = round2(gst_pct / 2)
fallback = {"cgst": half, "sgst": half, "igst": 0.0}
print(f"\u2705 Rate from Gst% field for {item.get('description')!r}: "
f"Gst%={gst_pct} → CGST={fallback['cgst']}% SGST={fallback['sgst']}% IGST={fallback['igst']}%")
# Priority 3: fall back to invoice-level total_cgst_rate / total_igst_rate
if not fallback:
h_cgst = safe_float(final_header.get("total_cgst_rate"))
h_sgst = safe_float(final_header.get("total_sgst_rate"))
h_igst = safe_float(final_header.get("total_igst_rate"))
if h_cgst > 0 or h_sgst > 0 or h_igst > 0:
fallback = {"cgst": h_cgst, "sgst": h_sgst, "igst": h_igst}
print(f"\u2705 Rate from invoice header for {item.get('description')!r}: "
f"CGST={h_cgst}% SGST={h_sgst}% IGST={h_igst}%")
if fallback:
cr_v = fallback["cgst"]
sr_v = fallback["sgst"]
ir_v = fallback["igst"]
if cr_v > 0: item["cgst_rate"] = cr_v
if sr_v > 0: item["sgst_rate"] = sr_v
if ir_v > 0: item["igst_rate"] = ir_v
# ----------------------------------------------------------------
# PHASE C — TAXABLE VALUE CALCULATION
#
# total_price is the FINAL GST-INCLUSIVE row total
# (taxable_value + CGST + SGST, or + IGST). This is the rightmost
# "Amount" column on the invoice, printed AFTER the GST columns.
#
# taxable_value is derived BACKWARD from total_price using the GST rate:
# taxable_value = total_price / (1 + gst_percent / 100)
#
# This is robust regardless of how the invoice expresses its discount
# (flat amount, percent, or no discount column at all) because the
# discount is already baked into total_price by the time it reaches
# this stage — we only need to strip the GST back out.
#
# Priority order for taxable_value:
# 1. Explicit Value/Taxable column extracted from the invoice
# 2. Backward-derive from total_price using gst_percent
# 3. Fallback to total_price as-is if gst_percent is unknown (no GST item)
# ----------------------------------------------------------------
qty = safe_float(item.get("quantity"))
unit_price = safe_float(item.get("unit_price"))
orig_total = safe_float(item.get("total_price")) # GST-inclusive
discount = safe_float(item.get("Discount"))
value_field = safe_float(item.get("Value"))
# taxable_value the model already copied straight from the invoice's
# own TAXABLE / TAXABLE AMT column (character-level OCR copy, per prompt).
# This is the printed value and must win over any backward calculation.
extracted_taxable = safe_float(item.get("taxable_value"))
# Reference only — gross pre-discount pre-GST amount, used as a last-resort fallback
plain_amount = round2(qty * unit_price) if qty > 0 and unit_price > 0 else 0.0
# total_price is taken as-is from the model (GST-inclusive). We only fill
# it in if missing/zero — we do NOT overwrite it with qty×rate, since it is
# expected to be larger than qty×rate by the GST amount.
if orig_total <= 0 and plain_amount > 0:
item["total_price"] = plain_amount
orig_total = plain_amount
print(f"⚠️ total_price missing for {item.get('description')!r}, "
f"falling back to qty×rate: {plain_amount} (GST not added — verify)")
total_gst_pct = cr_v + sr_v + ir_v # combined GST% for this item
# ── Derive taxable_value ────────────────────────────────────────
# Priority 1: taxable_value the model already copied directly from
# the invoice's own TAXABLE / TAXABLE AMT column. Trust the printed
# OCR value over any calculation — never recompute over it.
if extracted_taxable > 0:
taxable = round2(extracted_taxable)
# Priority 2: explicit Value column extracted by the model
elif value_field > 0:
taxable = round2(value_field)
# Priority 3: backward-derive from GST-inclusive total_price using GST rate
# (only used when the invoice has NO taxable/value column at all)
elif orig_total > 0 and total_gst_pct > 0:
taxable = round2(orig_total / (1 + total_gst_pct / 100))
print(f"✅ taxable_value derived for {item.get('description')!r}: "
f"{orig_total} / (1 + {total_gst_pct}%) = {taxable}")
# Priority 4: no GST rate known — assume total_price IS the taxable value
# (e.g. zero-rated or GST-exempt items)
else:
taxable = round2(orig_total) if orig_total > 0 else round2(plain_amount)
# Safety net: taxable must never be negative or zero when we have valid data
if taxable <= 0 and plain_amount > 0:
taxable = plain_amount
print(f"⚠️ taxable_value was ≤0, reset to plain_amount for "
f"{item.get('description')!r}: {taxable}")
item["taxable_value"] = taxable
# --- recalculate amounts ---
item["cgst_amount"] = round2(taxable * cr_v / 100)
item["sgst_amount"] = round2(taxable * sr_v / 100)
item["igst_amount"] = round2(taxable * ir_v / 100)
item["GST_AMT"] = round2(item["cgst_amount"] + item["sgst_amount"] + item["igst_amount"])
item["Gst%"] = round2(cr_v + sr_v + ir_v)
total_cgst_amount += item["cgst_amount"]
total_sgst_amount += item["sgst_amount"]
total_igst_amount += item["igst_amount"]
total_taxable += taxable
if cr_v > 0: cgst_rates_seen.add(cr_v)
if sr_v > 0: sgst_rates_seen.add(sr_v)
if ir_v > 0: igst_rates_seen.add(ir_v)
# --- update totals in final_header (Phase C computed values) ---
final_header["total_cgst_amount"] = round2(total_cgst_amount)
final_header["total_sgst_amount"] = round2(total_sgst_amount)
final_header["total_igst_amount"] = round2(total_igst_amount)
final_header["total_gst_amount"] = round2(total_cgst_amount + total_sgst_amount + total_igst_amount)
# ---------------------------------------------------------------
# 🔥 FOOTER TAX OVERRIDE
#
# If Gemini extracted explicit total_cgst_amount / total_sgst_amount
# from the invoice footer (e.g. "CGST 285.000", "SGST 285.000"),
# those printed values are authoritative and must NOT be replaced
# by Phase C's recalculated sums.
#
# We restore the Gemini-extracted footer totals if:
# 1. Gemini returned a non-zero value for that field
# 2. The value is plausible (> 0 and not wildly different from
# Phase C's sum — within 20% tolerance to catch OCR errors)
#
# This fixes invoices like TAPADIYA where:
# Invoice footer: CGST=285, SGST=285
# Phase C sum: CGST=299.43 (due to rounding across 97 items)
# ---------------------------------------------------------------
for _tax_field in ("total_cgst_amount", "total_sgst_amount", "total_igst_amount"):
_gemini_val = safe_float(
next((p.get(_tax_field) for p in all_pages_data if p.get(_tax_field)), None)
)
_phase_c_val = safe_float(final_header.get(_tax_field))
if _gemini_val > 0:
# Plausibility check: accept if within 20% of Phase C value
# (rejects wildly wrong OCR reads but accepts rounding differences)
if _phase_c_val == 0 or abs(_gemini_val - _phase_c_val) / max(_phase_c_val, 0.01) <= 0.20:
final_header[_tax_field] = round2(_gemini_val)
print(f"✅ Footer tax override: {_tax_field} = {_gemini_val} "
f"(Phase C had {_phase_c_val})")
else:
print(f"⚠️ Footer tax NOT used for {_tax_field}: "
f"Gemini={_gemini_val} vs Phase C={_phase_c_val} "
f"(>20% diff, keeping Phase C value)")
# Recompute total_gst_amount from the (possibly overridden) component totals
final_header["total_gst_amount"] = round2(
safe_float(final_header["total_cgst_amount"]) +
safe_float(final_header["total_sgst_amount"]) +
safe_float(final_header["total_igst_amount"])
)
# ── GST rate fields ──────────────────────────────────────────────────
# If all items share one rate → use that exact rate (clean output).
# If items have MIXED rates → compute effective weighted-average rate
# = (total_tax_amount / total_taxable_value) × 100
# This always produces a meaningful value rather than null.
# ────────────────────────────────────────────────────────────────────
if len(cgst_rates_seen) == 1:
final_header["total_cgst_rate"] = list(cgst_rates_seen)[0]
elif total_taxable > 0 and total_cgst_amount > 0:
final_header["total_cgst_rate"] = round2((total_cgst_amount / total_taxable) * 100)
if len(sgst_rates_seen) == 1:
final_header["total_sgst_rate"] = list(sgst_rates_seen)[0]
elif total_taxable > 0 and total_sgst_amount > 0:
final_header["total_sgst_rate"] = round2((total_sgst_amount / total_taxable) * 100)
if len(igst_rates_seen) == 1:
final_header["total_igst_rate"] = list(igst_rates_seen)[0]
elif total_taxable > 0 and total_igst_amount > 0:
final_header["total_igst_rate"] = round2((total_igst_amount / total_taxable) * 100)
# total_gst_rate: prefer IGST if present, else CGST + SGST
if final_header.get("total_igst_rate"):
final_header["total_gst_rate"] = final_header["total_igst_rate"]
elif final_header.get("total_cgst_rate") is not None and final_header.get("total_sgst_rate") is not None:
final_header["total_gst_rate"] = round2(
safe_float(final_header["total_cgst_rate"]) +
safe_float(final_header["total_sgst_rate"])
)
extracted_data = {
**final_header,
"items": deduped_items,
}
# ===============================
# 🔹 DETECT & SET CURRENCY CODE
# ===============================
currency_code = None
header_currency = str(extracted_data.get("currency_code") or "").upper()
if header_currency in ["INR", "USD", "EUR", "GBP", "JPY", "SGD"]:
currency_code = header_currency
invoice_amount = str(extracted_data.get("invoice_amount") or "")
if not currency_code:
if "₹" in invoice_amount:
currency_code = "INR"
elif "$" in invoice_amount:
currency_code = "USD"
elif "€" in invoice_amount:
currency_code = "EUR"
elif "£" in invoice_amount:
currency_code = "GBP"
elif "¥" in invoice_amount:
currency_code = "JPY"
if not currency_code:
currency_code = "INR"
extracted_data["currency_code"] = currency_code
# ✅ ADD THIS BLOCK — normalize unicode in all string fields
for key, value in extracted_data.items():
if isinstance(value, str):
extracted_data[key] = normalize_text(value)
# Also normalize item descriptions
for item in extracted_data.get("items", []):
for key, value in item.items():
if isinstance(value, str):
item[key] = normalize_text(value)
# 🔥 Split free-quantity items into separate paid/free records
# (handles both "20+2" combined quantity AND separate FREE-column
# invoices like QTY=50 / FREE=5 — see free_item_splitter.py)
extracted_data = split_free_items(extracted_data)
# 🔥 Inject invoice_id
extracted_data["invoice_id"] = invoice_id
# 🔥 Inject billing info (used by upload_image to save to DB)
extracted_data["_input_tokens"] = _total_input_tokens
extracted_data["_output_tokens"] = _total_output_tokens
extracted_data["_cost_usd"] = round(_invoice_cost, 6)
# 🔥 CLOSE CONNECTION
# ── GSTIN / name post-processing ─────────────────────────────────────
extracted_data = post_process_header_fields(extracted_data)
# ── Seller GSTIN cross-check (hardcoded lookup, seller_gstin_lookup.py) ──
# Switched from the Excel-based _apply_seller_master() to the
# hardcoded SELLER_GSTIN_MAP per instruction. _apply_seller_master()
# and _load_seller_master() are left defined below (unused) in case
# you want to revert or run both.
extracted_data = apply_seller_gstin_override(extracted_data)
# ── Deterministic OCR corrections (GSTIN/HSN/dates), ocr_corrector.py ──
# Runs after the hardcoded seller GSTIN override so that override
# wins for sellers in the map; this still fixes customer_gstin and
# any seller not in the map, plus HSN codes and — the actual fix
# you asked for — expiry_date / invoice_date / due_date / DC_date.
try:
extracted_data = apply_ocr_corrections(extracted_data, page_texts=page_texts)
except Exception as _ocr_fix_err:
print(f"⚠️ OCR correction failed (non-fatal): {_ocr_fix_err}")
# correct_date() outputs DD/MM/YYYY (slashes) natively — kept as-is.
# ── Consistency check (math-based, zero extra API calls) ──────
# Runs the same as before, but ALL consistency-check fields
# (invoice-level and per-item) are stripped before the data is
# returned, so none of them appear in the extracted JSON.
try:
extracted_data, _consistency_summary = run_consistency_checks(extracted_data)
except Exception as _cc_err:
print(f"⚠️ Consistency check failed (non-fatal): {_cc_err}")
# Hide consistency-check fields from the extracted JSON
extracted_data.pop("_invoice_review_reasons", None)
extracted_data.pop("_consistency_summary", None)
for _item in extracted_data.get("items", []):
_item.pop("_needs_review", None)
_item.pop("_review_reasons", None)
total_items_final = len(extracted_data.get("items", []))
inv_amt_final = extracted_data.get("invoice_amount", "0.00")
print(f"\n🎉 [EXTRACTION COMPLETE] Successfully processed: {total_items_final} items | Invoice amount: {inv_amt_final}", flush=True)
print(f"{'='*70}\n", flush=True)
return extracted_data
except Exception as e:
import traceback
print(f"\n❌ [EXTRACTION ERROR]: {e}", flush=True)
traceback.print_exc()
return {"error": str(e)}
finally:
if conn:
try:
conn.close()
except:
pass
@app.route("/process-invoice", methods=["POST"])
@api_key_required
def process_invoice():
try:
if "file" not in request.files:
return jsonify({"error": "No file part"}), 400
file = request.files["file"]
if file.filename == "":
return jsonify({"error": "No selected file"}), 400
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
file.save(filepath)
invoice_source = request.form.get("invoice_source", "electronic")
# Look up the caller's role via their API key for DMH-only features
_api_key = request.headers.get("X-API-Key")
_conn2 = get_db_connection()
_cur2 = _conn2.cursor(dictionary=True)
_cur2.execute(
"SELECT u.role FROM users u JOIN api_keys ak ON u.id = ak.user_id WHERE ak.api_key = %s",
(_api_key,)
)
_role_row = _cur2.fetchone()
_cur2.close()
_conn2.close()
_is_dmh = (_role_row["role"] == "dmh") if _role_row else False
extracted_data = extract_invoice_fields(filepath, invoice_source, is_dmh=_is_dmh)
# Strip internal billing keys before returning to API caller
for _k in ("_input_tokens", "_output_tokens", "_cost_usd"):
extracted_data.pop(_k, None)
return jsonify(extracted_data), 200
return jsonify({"error": "Invalid file type"}), 400
except Exception as e:
logging.error(f"Error during upload or extraction: {e}")
return jsonify({"error": "Internal Server Error"}), 500
@app.route("/usage-count", methods=["GET"])
@api_key_required
def get_usage_count():
api_key = request.headers.get("X-API-Key")
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
sql = "SELECT * FROM api_usage WHERE api_key = %s"
cursor.execute(sql, (api_key,))
usage_entry = cursor.fetchone()
cursor.close()
conn.close()
if usage_entry:
return jsonify(
{
"api_key": api_key,
"usage_count": usage_entry["count"],
"last_used": usage_entry["last_used"].strftime("%Y-%m-%d"),
}
)
else:
return jsonify({"error": "API key not found"}), 404
@app.route("/all-usage-counts", methods=["GET"])
@api_key_required
def get_all_usage_counts():
try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
sql = "SELECT * FROM api_usage"
cursor.execute(sql)
usage_entries = cursor.fetchall()
usage_data = []
for entry in usage_entries:
usage_data.append(
{
"api_key": entry["api_key"],
"usage_count": entry["count"],
"last_used": entry["last_used"].strftime("%Y-%m-%d"),
}
)
cursor.close()
conn.close()
return jsonify(usage_data), 200
except Exception as e:
return jsonify({"error": f"Internal Server Error: {str(e)}"}), 500
DMIN_API_KEY = os.getenv("ADMIN_API_KEY")
@app.route("/admin/dashboard")
def admin_dashboard():
if "user" not in session or session.get("role") != "admin":
flash("Unauthorized access.")
return redirect(url_for("login"))
try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
# fetch all users
cursor.execute("SELECT * FROM users")
users = cursor.fetchall()
# fetch all api_keys
cursor.execute("SELECT * FROM api_keys")
api_keys = cursor.fetchall()
cursor.close()
conn.close()
# group api_keys by user_id
api_keys_dict = {}
for key in api_keys:
uid = key["user_id"]
api_keys_dict.setdefault(uid, []).append(key)
# build user_activity list and include phone
user_activity = []
for u in users:
u_id = u["id"]
user_activity.append(
{
"username": u["username"],
"email": u["email"],
"phone": u.get("phone", "—"), # ← new phone field
"invoices_extracted": u.get("invoices_extracted", 0),
"account_limit": u.get("account_limit", 3),
"api_keys": api_keys_dict.get(u_id, []),
"api_keys": api_keys_dict.get(u_id, []),
"user_id": u_id,
}
)
return render_template("admin_dashboard.html", user_activity=user_activity)
except Exception as e:
flash(f"Error loading dashboard: {e}")
return render_template("admin_dashboard.html", user_activity=[])
@app.route("/admin/update-user-limit", methods=["POST"])
def update_user_limit():
try:
data = request.get_json()
user_id = data.get("user_id")
new_account_limit = data.get("new_account_limit")
app.logger.info(f"Request data: {data}")
app.logger.info(
f"Received user_id: {user_id}, New account limit: {new_account_limit}"
)
if not user_id or new_account_limit is None:
return jsonify({"error": "Missing required parameters"}), 400
try:
user_id = int(user_id)
new_account_limit = int(new_account_limit)
if new_account_limit < 0:
return (
jsonify({"error": "Account limit must be a positive integer"}),
400,
)
except ValueError:
return jsonify({"error": "Account limit must be a valid integer"}), 400
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
sql = "SELECT * FROM users WHERE id = %s"
cursor.execute(sql, (user_id,))
user = cursor.fetchone()
if not user:
cursor.close()
conn.close()
return jsonify({"error": "User not found"}), 404
app.logger.info(f"User found: {user}")
sql_update = "UPDATE users SET account_limit = %s WHERE id = %s"
cursor.execute(sql_update, (new_account_limit, user_id))
conn.commit()
modified_count = cursor.rowcount
cursor.close()
conn.close()
app.logger.info(f"Update result: {modified_count}")
if modified_count == 0:
return jsonify({"error": "No changes made"}), 404
app.logger.info(f"User {user_id}'s account limit updated: {new_account_limit}")
return (
jsonify(
{
"message": f"Account limit updated to {new_account_limit} for user {user_id}"
}
),
200,
)
except Exception as e:
app.logger.error(f"Error updating user limit: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/some-a-endpoint", methods=["GET"])
def some_api_endpoint():
api_key = request.headers.get("X-API-Key")
if not api_key:
return jsonify({"error": "API key is missing"}), 400
print(f"Received API Key: {api_key}")
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
sql = "SELECT * FROM api_usage WHERE api_key = %s"
cursor.execute(sql, (api_key,))
current_data = cursor.fetchone()
print(f"Current Data: {current_data}")
if not current_data:
cursor.close()
conn.close()
return jsonify({"error": "API key not found"}), 404
sql_update = "UPDATE api_usage SET count = count + 1 WHERE api_key = %s"
cursor.execute(sql_update, (api_key,))
conn.commit()
cursor.execute(sql, (api_key,))
updated_data = cursor.fetchone()
print(f"Updated Data After Increment: {updated_data}")
cursor.close()
conn.close()
return jsonify(
{"message": "API key usage incremented successfully", "data": updated_data}
)
@app.route("/", methods=["GET"])
def index():
if "user" in session:
return redirect(
url_for("home_logged_in")
) # Redirect to proper logged-in homepage
return render_template("home.html", logged_in=False)
# New Invoice Route
@app.route("/invoice")
def invoice():
return render_template("invoice.html") # After login, redirect to upload_image
@app.route("/passport")
def passport():
return render_template("passport.html")
from email_validator import validate_email, EmailNotValidError
import phonenumbers
from phonenumbers import NumberParseException
def validate_user_email(email):
try:
v = validate_email(email)
return v.email, None
except EmailNotValidError as e:
return None, str(e)
def validate_phone_number(raw_phone, default_region="IN"):
try:
pn = phonenumbers.parse(raw_phone, default_region)
if not phonenumbers.is_valid_number(pn):
return None, "Phone number is not valid"
e164 = phonenumbers.format_number(pn, phonenumbers.PhoneNumberFormat.E164)
return e164, None
except NumberParseException as e:
return None, str(e)
@app.route("/signup", methods=["GET", "POST"])
def signup():
if request.method == "POST":
username = request.form["username"].strip()
email_in = request.form["email"].strip()
phone_in = request.form.get("phone", "").strip()
password = request.form["password"] # plain password
# 1) Validate email
email, email_err = validate_user_email(email_in)
if email_err:
flash(f"Invalid email address: {email_err}", "error")
return redirect(url_for("signup"))
# 2) Validate phone
phone, phone_err = validate_phone_number(phone_in)
if phone_err:
flash(f"Invalid phone number: {phone_err}", "error")
return redirect(url_for("signup"))
# 3) Store password PLAIN (no hashing)
plain_password = password
try:
conn = get_db_connection()
cursor = conn.cursor()
sql = """
INSERT INTO users (username, email, password, phone)
VALUES (%s, %s, %s, %s)
"""
cursor.execute(sql, (username, email, plain_password, phone))
conn.commit()
cursor.close()
conn.close()
flash("Sign up successful! Please log in.", "success")
return redirect(url_for("login"))
except Exception as e:
flash(f"Unexpected Error: {e}", "error")
return render_template("appsignup.html")
@app.route("/forgot_password", methods=["GET", "POST"])
def forgot_password():
if request.method == "POST":
email = request.form["email"]
try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
sql = "SELECT * FROM users WHERE email = %s"
cursor.execute(sql, (email,))
user = cursor.fetchone()
cursor.close()
conn.close()
if user:
session["reset_email"] = email
flash("Please enter your new password.")
return redirect(url_for("reset_password"))
else:
flash("No account found with this email.")
except Exception as e:
flash(f"Error: {e}")
return render_template("appforget.html")
from flask import render_template
from zoneinfo import ZoneInfo
#def to_ist(utc_time):
# return utc_time.replace(tzinfo=ZoneInfo("UTC")).astimezone(ZoneInfo("Asia/Kolkata"))
def to_ist(utc_dt):
# If naive, assume it's UTC
if utc_dt.tzinfo is None:
utc_dt = utc_dt.replace(tzinfo=ZoneInfo("UTC"))
# Convert to IST
ist_dt = utc_dt.astimezone(ZoneInfo("Asia/Kolkata"))
return ist_dt
UPLOAD_FOLDER = os.path.join(os.getcwd(), "uploads", "invoices")
@app.route("/view-invoice/<int:invoice_id>")
def view_invoice(invoice_id):
user_id = session.get("user_id")
if not user_id:
return redirect(url_for("login"))
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute(
"""
SELECT extracted_data, image_name, timestamp
FROM extraction_history
WHERE id = %s AND user_id = %s
""",
(invoice_id, user_id)
)
invoice = cursor.fetchone()
cursor.close()
conn.close()
if not invoice:
return "Invoice not found", 404
if not invoice["extracted_data"]:
return "JSON extraction not available for this invoice", 404
extracted_json = json.loads(invoice["extracted_data"])
return render_template(
"view_invoice_json.html",
invoice_json=json.dumps(extracted_json,indent=4),
image_name=invoice["image_name"],
timestamp=invoice["timestamp"],
)
@app.route("/invoice-history")
def invoice_history_page():
user_id = session.get("user_id")
if not user_id:
return redirect(url_for("login"))
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute(
"""
SELECT id, timestamp, image_name
FROM extraction_history
WHERE user_id = %s
AND extracted_data IS NOT NULL
ORDER BY timestamp DESC
""",
(user_id,)
)
rows = cursor.fetchall()
cursor.close()
conn.close()
invoice_history = []
for row in rows:
invoice_history.append({
"id": row["id"],
"timestamp_str": row["timestamp"].strftime("%d-%m-%Y %I:%M:%S %p"),
"image_name": row["image_name"],
})
return render_template("view_history.html", invoice_history=invoice_history)
@app.route("/invoice-json/<int:invoice_id>")
def invoice_json(invoice_id):
user_id = session.get("user_id")
if not user_id:
return redirect(url_for("login"))
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute(
"""
SELECT extracted_data
FROM extraction_history
WHERE id = %s AND user_id = %s
""",
(invoice_id, user_id)
)
row = cursor.fetchone()
cursor.close()
conn.close()
if not row or not row["extracted_data"]:
return "Extraction not available", 404
extracted_data = json.loads(row["extracted_data"])
return render_template("view_invoice_json.html", extracted_data=extracted_data)
@app.route("/reset_password", methods=["GET", "POST"])
def reset_password():
if "reset_email" not in session:
flash("Invalid reset attempt.")
return redirect(url_for("forgot_password"))
if request.method == "POST":
new_password = request.form["password"] # plain password
try:
conn = get_db_connection()
cursor = conn.cursor()
sql = "UPDATE users SET password = %s WHERE email = %s"
cursor.execute(sql, (new_password, session["reset_email"]))
conn.commit()
cursor.close()
conn.close()
session.pop("reset_email", None)
flash("Password reset successfully.")
return redirect(url_for("login"))
except Exception as e:
flash(f"Error: {e}")
return render_template("appreset.html")
def get_user_from_db(login_input, password):
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute(
"""
SELECT * FROM users
WHERE (username = %s OR email = %s)
""",
(login_input, login_input),
)
user = cursor.fetchone()
cursor.close()
conn.close()
# password check (plain text as per your current system)
if user and user["password"] == password:
return user
return None
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
login_input = request.form.get("username")
password = request.form.get("password")
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute(
"SELECT * FROM users WHERE username=%s OR email=%s",
(login_input, login_input),
)
user = cursor.fetchone()
cursor.close()
conn.close()
is_password_valid = False
if user and user.get("password"):
if password == user["password"]:
is_password_valid = True
elif user["password"].startswith("$2b$") or user["password"].startswith("$2a$"):
try:
import bcrypt
is_password_valid = bcrypt.checkpw(password.encode("utf-8"), user["password"].encode("utf-8"))
except Exception:
pass
if user and is_password_valid:
session.clear()
session["user_id"] = user["id"]
session["user"] = user["username"] # ✅ THIS FIXES IT
session["role"] = user.get("role", "user")
if user["role"] == "dmh":
return redirect(url_for("dmh_dashboard"))
else:
return redirect(url_for("dashboard"))
flash("Invalid login details", "error")
return render_template("applogin.html")
import uuid
@app.route("/upload-invoice", methods=["POST"])
def upload_invoice():
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"))
# 1️⃣ Get uploaded file
file = request.files["invoice"]
file_path = save_file(file)
# 2️⃣ Convert PDF → images
if file_path.lower().endswith(".pdf"):
images = pdf_to_images_standalone(file_path, dpi=300)
else:
images = [Image.open(file_path)]
# 3️⃣ Run OCR pipeline
is_dmh = (role == "dmh") # ✅ DMH-only PO features
extracted_data = extract_invoice_fields(file_path, is_dmh=is_dmh)
if not extracted_data:
extracted_data = {}
# 4️⃣ Store in DB
pages_extracted = len(extracted_data)
extraction_type = "invoice"
image_name = os.path.basename(file_path)
extracted_json = json.dumps(extracted_data)
ist_now = datetime.now(ZoneInfo("Asia/Kolkata")).replace(tzinfo=None)
conn=get_db_connection()
cursor = conn.cursor()
cursor.execute(
"""
INSERT INTO extraction_history
(user_id, timestamp, image_name, pages_extracted, extraction_type, extracted_data)
VALUES (%s, %s, %s, %s, %s, %s)
""",
(
user_id,
ist_now(),
image_name,
pages_extracted,
extraction_type,
extracted_json
),
)
db.commit()
cursor.close()
return redirect(url_for("view_history"))
import fitz # PyMuPDF
from PIL import Image
import io
@app.route("/upload_image", methods=["GET", "POST"])
def upload_image():
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"))
conn = None
cursor = None
try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT * FROM users WHERE username = %s", (session["user"],))
user = cursor.fetchone()
if not user:
flash("User not found.", "error")
return redirect(url_for("login"))
total_extracted = user.get("invoices_extracted", 0) + user.get("passports_extracted", 0)
extraction_limit = user.get("account_limit") or 50
if total_extracted >= extraction_limit:
flash("You have reached your extraction limit.", "error")
return redirect(url_for("dashboard"))
if request.method == "POST":
# Prevent rapid double-clicks (within 2s), but auto-expire lock after 60s so users are never stuck
import time
now_ts = time.time()
if session.get("processing", False) and (now_ts - session.get("processing_start", 0) < 60):
flash("Please wait, an extraction is already in progress.", "warning")
return redirect(url_for("dashboard"))
doc_type = request.form.get("doc_type")
if doc_type not in ["invoice", "passport"]:
flash("Invalid document type.", "error")
return redirect(url_for("dashboard"))
file = request.files.get("file")
if not file or not allowed_file(file.filename):
flash("Invalid file. Upload PDF or Image.", "error")
return redirect(url_for("dashboard"))
# ✅ FIX: Use UUID to avoid filename conflicts on second upload
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)
session["processing"] = True
session["processing_start"] = now_ts
# ============================
# INVOICE FLOW
# ============================
if doc_type == "invoice":
ext = original_filename.lower()
invoice_source = "manual" if ext.endswith((".jpg", ".jpeg", ".png")) else "email"
# ✅ FIX: Don't generate invoice_id here — extractor generates it
# invoice_id is returned inside extracted_data
is_dmh = (role == "dmh") # ✅ DMH-only PO features
extracted_data = extract_invoice_fields(file_path, invoice_source, is_dmh=is_dmh)
invoice_id = extracted_data.get("invoice_id") if isinstance(extracted_data, dict) else None
update_field = "invoices_extracted"
# ============================
# PASSPORT FLOW
# ============================
else:
extracted_data = extract_passport_fields(file_path)
update_field = "passports_extracted"
invoice_id = None
invoice_source = None
if not extracted_data or "error" in extracted_data:
err_msg = extracted_data.get("error", "Unknown extraction error") if isinstance(extracted_data, dict) else "No data returned by extractor"
print(f"❌ [UPLOAD FAILED] {err_msg}", flush=True)
flash(f"Extraction failed: {err_msg}", "error")
session["processing"] = False
return redirect(url_for("dashboard"))
page_count = len(extracted_data)
# ── Pull billing metadata out before saving JSON ──────────────
_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)
cursor.execute(
f"UPDATE users SET {update_field} = {update_field} + %s WHERE username = %s",
(page_count, 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,
page_count,
doc_type,
json.dumps(extracted_data),
file_path,
_input_tokens,
_output_tokens,
_cost_usd,
),
)
conn.commit()
session["processing"] = False
return render_template(
"result.html",
json_data=json.dumps(extracted_data, indent=4),
invoice_id=invoice_id,
)
return redirect(url_for("dashboard"))
except Exception as e:
logging.error(f"Upload error: {e}", exc_info=True)
flash(f"Error: {e}", "error")
return redirect(url_for("dashboard"))
finally:
if cursor:
cursor.close()
if conn:
conn.close()
session["processing"] = False
# ✅ FIX: Always delete temp file after processing
try:
if "file_path" in locals() and os.path.exists(file_path):
os.remove(file_path)
print(f"✅ Temp file deleted: {file_path}")
except Exception as e:
print(f"⚠️ Could not delete temp file: {e}")
@app.route("/download_file", methods=["POST"])
def download_file():
invoice_data = request.form.get("json_data")
file_format = request.form.get("file_format")
if not invoice_data:
return "No data available for download", 400
try:
parsed_data = json.loads(invoice_data)
except json.JSONDecodeError:
return "Invalid JSON data", 400
if file_format == "json":
json_str = json.dumps(parsed_data, indent=4)
buffer = io.BytesIO(json_str.encode("utf-8"))
buffer.seek(0)
return send_file(
buffer,
as_attachment=True,
download_name="invoice_data.json",
mimetype="application/json",
)
elif file_format == "excel":
if isinstance(parsed_data, dict) and all(
key.startswith("page_") for key in parsed_data.keys()
):
data_list = []
for key, value in parsed_data.items():
if isinstance(value, dict):
value["page"] = key
data_list.append(value)
df = pd.DataFrame(data_list)
else:
df = pd.DataFrame([parsed_data])
buffer = io.BytesIO()
with pd.ExcelWriter(buffer, engine="xlsxwriter") as writer:
df.to_excel(writer, index=False)
buffer.seek(0)
return send_file(
buffer,
as_attachment=True,
download_name="invoice_data.xlsx",
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
@app.route("/dashboard", methods=["GET", "POST"])
def dashboard():
if "user" not in session:
if request.is_json:
return jsonify({"error": "Unauthorized access. Please log in."}), 401
flash("Please login first.", "warning")
return redirect(url_for("login"))
if session.get("role") == "dmh":
return redirect(url_for("dmh_dashboard"))
session["processing"] = False
conn = None
cursor = None
try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
sql = "SELECT * FROM users WHERE username = %s"
cursor.execute(sql, (session["user"],))
user = cursor.fetchone()
if not user:
flash("User not found.", "error")
if request.is_json:
return jsonify({"error": "User not found."}), 404
return redirect(url_for("login"))
username = user.get("username", "N/A")
email = user.get("email", "N/A")
invoices_count = user.get("invoices_extracted", 0)
passports_count = user.get("passports_extracted", 0)
sql_history = "SELECT * FROM extraction_history WHERE user_id = %s ORDER BY timestamp DESC"
cursor.execute(sql_history, (user["id"],))
history = cursor.fetchall()
sql_api_key = "SELECT api_key FROM api_keys WHERE user_id = %s"
cursor.execute(sql_api_key, (user["id"],))
user_api_key = cursor.fetchone()
api_key = user_api_key["api_key"] if user_api_key else None
formatted_history = [
{
"timestamp_str": entry["timestamp"].strftime("%Y-%m-%d %H:%M:%S"),
"image_name": entry.get("image_name", "Unknown"),
"pages_extracted": entry.get("pages_extracted", 0),
"extraction_type": entry.get("extraction_type", "N/A"),
}
for entry in history
]
if request.is_json:
return jsonify(
{
"username": username,
"email": email,
"invoices_count": invoices_count,
"passports_count": passports_count,
"history": formatted_history,
"api_key": api_key,
}
)
return render_template(
"dashboard.html",
username=username,
email=email,
invoices_count=invoices_count,
passports_count=passports_count,
history=formatted_history,
api_key=api_key,
)
except mysql.connector.Error as db_err:
logging.error(f"Database error: {db_err}", exc_info=True)
flash(f"Database error: {db_err}", "error")
if request.is_json:
return jsonify({"error": str(db_err)}), 500
return render_template(
"dashboard.html",
username="N/A",
email="N/A",
invoices_count=0,
passports_count=0,
history=[],
api_key=None,
)
except Exception as e:
logging.error(f"Unexpected error in dashboard: {e}", exc_info=True)
flash(f"Error: {e}", "error")
if request.is_json:
return jsonify({"error": str(e)}), 500
return render_template(
"dashboard.html",
username="N/A",
email="N/A",
invoices_count=0,
passports_count=0,
history=[],
api_key=None,
)
finally:
if cursor:
cursor.close()
if conn:
conn.close()
@app.route("/dmh/dashboard")
def dmh_dashboard():
if session.get("role") != "dmh":
return redirect(url_for("login"))
session["processing"] = False
return render_template("dmh_dashboard.html")
@app.route("/view_history")
def view_history():
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"))
try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute(
"SELECT id FROM users WHERE username = %s",
(session["user"],)
)
user = cursor.fetchone()
if not user:
cursor.close()
conn.close()
return redirect(url_for("login"))
cursor.execute(
"SELECT * FROM extraction_history WHERE user_id = %s ORDER BY timestamp DESC",
(user["id"],)
)
invoice_history = cursor.fetchall()
formatted_history = []
for entry in invoice_history:
utc_time = entry["timestamp"]
if utc_time.tzinfo is None:
utc_time = utc_time.replace(tzinfo=timezone.utc)
ist_time = utc_time.astimezone(ZoneInfo("Asia/Kolkata"))
entry["timestamp_str"] = ist_time.strftime(
"%d-%m-%Y %I:%M:%S %p"
)
formatted_history.append(entry)
cursor.close()
conn.close()
return render_template(
"view_history.html",
invoice_history=formatted_history
)
except Exception as e:
print("Error:", e)
return "Something went wrong", 500
@app.route("/api/extract_invoice", methods=["POST"])
def api_extract_invoice():
if "api_key" not in request.headers:
return jsonify({"error": "Missing API key"}), 401
api_key = request.headers["api_key"]
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
sql = "SELECT * FROM api_keys WHERE api_key = %s"
cursor.execute(sql, (api_key,))
api_key_record = cursor.fetchone()
if not api_key_record:
cursor.close()
conn.close()
return jsonify({"error": "Invalid API key"}), 403
file = request.files.get("file")
if not file or not allowed_file(file.filename):
cursor.close()
conn.close()
return (
jsonify(
{"error": "Invalid file type. Please upload a valid PDF or image."}
),
400,
)
filename = secure_filename(file.filename)
file_path = os.path.join(app.config["UPLOAD_FOLDER"], filename)
file.save(file_path)
# Look up the caller's role to apply DMH-only features
cursor.execute("SELECT role FROM users WHERE id = %s", (api_key_record["user_id"],))
caller_role_row = cursor.fetchone()
caller_is_dmh = (caller_role_row["role"] == "dmh") if caller_role_row else False
invoice_data = extract_invoice_fields(file_path, is_dmh=caller_is_dmh)
# Strip internal billing keys before returning to API caller
for _k in ("_input_tokens", "_output_tokens", "_cost_usd"):
invoice_data.pop(_k, None)
if invoice_data:
sql_update = (
"UPDATE users SET invoices_extracted = invoices_extracted + 1 WHERE id = %s"
)
cursor.execute(sql_update, (api_key_record["user_id"],))
conn.commit()
cursor.close()
conn.close()
return jsonify({"success": True, "invoice_data": invoice_data}), 200
else:
cursor.close()
conn.close()
return (
jsonify({"success": False, "error": "Failed to extract invoice data"}),
500,
)
@app.route("/generate_api_key", methods=["POST"])
def generate_api_key():
if "user" not in session:
return jsonify({"error": "Unauthorized. Please log in first."}), 401
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
sql = "SELECT id FROM users WHERE username = %s"
cursor.execute(sql, (session["user"],))
user = cursor.fetchone()
if not user:
cursor.close()
conn.close()
return jsonify({"error": "User not found."}), 404
sql_check = "SELECT * FROM api_keys WHERE user_id = %s"
cursor.execute(sql_check, (user["id"],))
existing_api_key = cursor.fetchone()
if existing_api_key:
cursor.close()
conn.close()
return jsonify({"error": "You have already generated an API key."}), 400
api_key = secrets.token_hex(32)
sql_insert = (
"INSERT INTO api_keys (user_id, api_key, created_at) VALUES (%s, %s, %s)"
)
cursor.execute(sql_insert, (user["id"], api_key, datetime.utcnow()))
conn.commit()
cursor.close()
conn.close()
return jsonify({"api_key": api_key, "success": True})
@app.route("/logout")
def logout():
session.pop("user", None)
flash("Logged out successfully!")
return redirect(url_for("index"))
@app.route("/admin/set-account-limit", methods=["POST"])
def set_account_limit():
try:
data = request.get_json()
new_manual_limit = data.get("manual_limit", 50)
new_api_limit = data.get("api_limit", 50)
if new_manual_limit < 0 or new_api_limit < 0:
return jsonify({"error": "Limits must be positive integers"}), 400
total_account_limit = new_manual_limit + new_api_limit
conn = get_db_connection()
cursor = conn.cursor()
sql = "UPDATE users SET manual_limit = %s, api_limit = %s, account_limit = %s"
cursor.execute(sql, (new_manual_limit, new_api_limit, total_account_limit))
conn.commit()
modified_count = cursor.rowcount
cursor.close()
conn.close()
if modified_count == 0:
return jsonify({"message": "No users updated"}), 404
return (
jsonify(
{
"message": f"Account limits set to {total_account_limit} for all users"
}
),
200,
)
except Exception as e:
app.logger.error(f"Error setting account limits: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/get_api_key", methods=["GET"])
def get_api_key():
if "user" not in session:
return jsonify({"error": "Unauthorized. Please log in first."}), 401
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
sql = "SELECT id FROM users WHERE username = %s"
cursor.execute(sql, (session["user"],))
user = cursor.fetchone()
if not user:
cursor.close()
conn.close()
return jsonify({"error": "User not found."}), 404
sql_api = "SELECT api_key FROM api_keys WHERE user_id = %s"
cursor.execute(sql_api, (user["id"],))
api_key = cursor.fetchone()
cursor.close()
conn.close()
if api_key:
return jsonify({"api_key": api_key["api_key"], "success": True})
else:
return jsonify({"error": "No API key found."}), 404
@app.route("/api/routes", methods=["GET"])
def list_routes():
routes = []
for rule in app.url_map.iter_rules():
routes.append(
{"endpoint": rule.endpoint, "methods": list(rule.methods), "url": str(rule)}
)
return jsonify({"routes": routes})
@app.route("/admin/billing", methods=["GET"])
def admin_billing():
"""Admin view — shows per-user Qwen billing totals."""
if "user" not in session or session.get("role") != "admin":
flash("Unauthorized access.")
return redirect(url_for("login"))
try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute(
"""
SELECT
u.username,
u.email,
COUNT(h.id) AS total_extractions,
COALESCE(SUM(h.input_tokens), 0) AS total_input_tokens,
COALESCE(SUM(h.output_tokens), 0) AS total_output_tokens,
COALESCE(SUM(h.cost_usd), 0) AS total_cost_usd
FROM users u
LEFT JOIN extraction_history h ON u.id = h.user_id
GROUP BY u.id, u.username, u.email
ORDER BY total_cost_usd DESC
"""
)
rows = cursor.fetchall()
cursor.close()
conn.close()
return jsonify({"billing": rows}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/admin/billing/total", methods=["GET"])
def admin_billing_total():
"""Admin view — overall Qwen spend summary."""
if "user" not in session or session.get("role") != "admin":
return jsonify({"error": "Unauthorized"}), 401
try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute(
"""
SELECT
COALESCE(SUM(input_tokens), 0) AS total_input_tokens,
COALESCE(SUM(output_tokens), 0) AS total_output_tokens,
COALESCE(SUM(cost_usd), 0) AS total_cost_usd,
COUNT(id) AS total_extractions
FROM extraction_history
"""
)
row = cursor.fetchone()
cursor.close()
conn.close()
return jsonify(row), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
port = int(os.getenv("PORT", 8080))
@app.route("/about")
def about():
return render_template("about.html")
@app.route("/pricing")
def pricing():
return render_template("pricing.html")
@app.route("/contact_sales")
def contact_sales():
return render_template("about.html")
# Add this at the end of your application.py and run once
import os
# from dotenv import load_dotenv
# load_dotenv()
from flask import Flask, request, jsonify
from dotenv import load_dotenv
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Print current working directory to confirm
print("Current working directory:", os.getcwd())
# Load .env file
load_dotenv() # Looks for .env in the current working directory
# Email config
# Email Configuration
EMAIL_ADDRESS = os.getenv("EMAIL_ADDRESS") # e.g., 'your_email@gmail.com'
EMAIL_PASSWORD = os.getenv("EMAIL_PASSWORD") # e.g., Gmail app-specific password
RECIPIENT_EMAIL = os.getenv("RECIPIENT_EMAIL") # e.g., 'recipient@example.com'
SMTP_SERVER = "smtp.gmail.com" # Adjust for your email provider
SMTP_PORT = 587
def send_email(email, contact, message):
missing_configs = []
if not EMAIL_ADDRESS:
missing_configs.append("EMAIL_ADDRESS")
if not EMAIL_PASSWORD:
missing_configs.append("EMAIL_PASSWORD")
if not RECIPIENT_EMAIL:
missing_configs.append("RECIPIENT_EMAIL")
if not SMTP_SERVER:
missing_configs.append("SMTP_SERVER")
if not SMTP_PORT:
missing_configs.append("SMTP_PORT")
if missing_configs:
print(
f"Email configuration missing: {', '.join(missing_configs)}. Check .env file."
)
return False
msg = MIMEMultipart()
msg["From"] = EMAIL_ADDRESS
msg["To"] = RECIPIENT_EMAIL
msg["Subject"] = "New Query Submission from AI Infinite"
# Format body nicely whether it's contact or demo
if contact is not None:
body = f"""
Hello,
A new query has been received through the AI Infinite contact form:
Email: {email}
Contact Number: {contact or 'Not provided'}
Message: {message}
Thank you,
AI Infinite Team
"""
else:
body = message # If it's demo, just use the already formatted message
msg.attach(MIMEText(body, "plain"))
try:
server = smtplib.SMTP(SMTP_SERVER, int(SMTP_PORT))
server.starttls()
server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
server.sendmail(EMAIL_ADDRESS, RECIPIENT_EMAIL, msg.as_string())
server.quit()
print("Email sent successfully")
return True
except Exception as e:
print(f"Email error: {e}")
return False
@app.route("/submit", methods=["POST"])
def submit_query():
print("Received form submission")
email = request.form.get("email")
contact = request.form.get("contact")
message = request.form.get("message")
print(f"Form data: email={email}, contact={contact}, message={message}")
if not email or not message:
print("Validation failed: Email or message missing")
return (
jsonify({"success": False, "message": "Email and message are required"}),
400,
)
try:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute(
"INSERT INTO contact_queries (email, contact, message) VALUES (%s, %s, %s)",
(email, contact, message),
)
conn.commit()
print("Query stored in database")
except Exception as e:
print(f"Database error: {e}")
return jsonify({"success": False, "message": "Error storing query"}), 500
finally:
cursor.close()
conn.close()
if send_email(email, contact, message):
print("Email sent successfully")
return jsonify({"success": True, "message": "Query stored and email sent"})
else:
print("Email sending failed")
return (
jsonify(
{"success": False, "message": "Query stored, but failed to send email"}
),
200,
)
@app.route("/schedule", methods=["POST"])
def schedule_demo():
print("Received demo submission")
name = request.form.get("name")
email = request.form.get("company-email")
timezone = request.form.get("timezone")
if not email:
print("Validation failed: Email missing")
return jsonify({"success": False, "message": "Email is required"}), 400
message = (
"Hello,\n"
"A new demo request has been issued by\n\n"
f"Name: {name or 'Not provided'}\n"
f"Email: {email}\n"
f"Timezone: {timezone or 'Not specified'}\n\n"
"Thank you."
)
if send_email(email, None, message):
print("Demo email sent successfully")
return jsonify(
{"success": True, "message": "Demo request processed and email sent"}
)
else:
print("Demo email sending failed")
return (
jsonify(
{
"success": False,
"message": "Demo request processed, but failed to send email",
}
),
200,
)
@app.route("/home")
def home_logged_in():
if "user" not in session:
print("User not in session. Redirecting to index.")
return redirect(url_for("index"))
print(f"User is in session: {session['user']}")
return render_template("home.html", logged_in=True, username=session["user"])
@app.context_processor
def inject_user():
return {"logged_in": "user" in session, "username": session.get("user")}
from datetime import datetime
if __name__ == "__main__":
port = int(os.getenv("PORT", 8080))
try:
app.run(host="0.0.0.0", port=port, debug=True)
except OSError:
print(f"Port {port} busy, attempting fallback port 5000...")
app.run(host="0.0.0.0", port=5000, debug=True)