feat: major platform upgrade — AI extraction pipeline, responsive UI, admin chatbot enhancements
CRITICAL FIXES - Fix blank pages: useCallback declared after useEffect in all 5 pages - Fix showToast undefined everywhere (ToastContext exported addToast not showToast) - Fix admin doc upload always 422 (missing doc_key + doc_label form fields) - Fix audit log wrong field names (log.details -> log.detail, remove user_agent) - Fix SPA catch-all missing in main.py (direct URL access was 404) - Fix chatbot using broken nvidia free model -> llama-3.3-70b AI EXTRACTION PIPELINE - 3-stage pipeline: Stage1 native text (free) -> Stage2 Tesseract OCR (free CPU) -> Stage3 Qwen vision (paid) - Tesseract installed with eng+hin bilingual support, psm6, 2.5x DPI - Scanned PDF fallback via PyMuPDF page render - Blank template fallback: returns form_type/purpose/tax_year instead of empty - Improved prompt: extracts actual document field names, no predefined terms - Auto-poll UI: shows Processing spinner when extraction is running - backfill_extraction.py: re-process all docs, fixed empty-dict-as-None bug ADMIN DASHBOARD - Pending docs split into Pending Personal + Pending Business stat cards - User cards show typed badges: N personal / N business instead of generic N pending - Backend returns pending_personal, pending_business, pending_docs per user ADMIN USER DETAIL - Doc count chips in user info bar: personal / business / returns / total - Doc name bold 15px, date with calendar icon + TY chip, status as colored badges - Responsive layout: doc-review-layout CSS classes replace inline flex styles - Filing Timeline sidebar stacks above doc list on mobile - AI Summary: bold labels and values, blank template shows metadata CHATBOT ENHANCEMENTS - Ask anything free-text input on menu screen (both admin and user chatbots) - Admin: live context with latest uploads by date, new users today - Admin: per-user activity lookup by name/email (docs + audit log) - New endpoint: /api/chatbot/admin-user-context - ExpandableSummaryBlock + ExpandableValue: bold navy field labels and values RESPONSIVENESS - components.css: 480px/640px/768px breakpoints for all pages - Admin table, stat cards, tabs, toasts, FAB all properly responsive - Auth shell stacks on mobile correctly
This commit is contained in:
@@ -479,7 +479,7 @@ def list_users_for_admin(
|
||||
"""
|
||||
from sqlalchemy import func as sqlfunc
|
||||
|
||||
def _pending_count(uid: int) -> int:
|
||||
def _pending_count(uid: int) -> dict:
|
||||
p = db.query(sqlfunc.count(PersonalDocument.id)).filter(
|
||||
PersonalDocument.user_id == uid,
|
||||
PersonalDocument.review_status == "pending",
|
||||
@@ -490,7 +490,7 @@ def list_users_for_admin(
|
||||
BusinessDocument.review_status == "pending",
|
||||
BusinessDocument.deleted_at == None,
|
||||
).scalar() or 0
|
||||
return p + b
|
||||
return {"pending_personal": p, "pending_business": b, "pending_docs": p + b}
|
||||
|
||||
if current_user.role == UserRole.super_admin:
|
||||
q = db.query(UserModel)
|
||||
@@ -503,12 +503,12 @@ def list_users_for_admin(
|
||||
return {
|
||||
"users": [
|
||||
{
|
||||
"id": u.id,
|
||||
"name": u.name,
|
||||
"email": u.email,
|
||||
"phone": u.phone,
|
||||
"role": u.role.value if hasattr(u.role, "value") else str(u.role),
|
||||
"pending_docs": _pending_count(u.id),
|
||||
"id": u.id,
|
||||
"name": u.name,
|
||||
"email": u.email,
|
||||
"phone": u.phone,
|
||||
"role": u.role.value if hasattr(u.role, "value") else str(u.role),
|
||||
**_pending_count(u.id), # inlines pending_personal, pending_business, pending_docs (total)
|
||||
}
|
||||
for u in users
|
||||
],
|
||||
|
||||
+31
-74
@@ -1,6 +1,6 @@
|
||||
import os
|
||||
import logging
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import FileResponse
|
||||
@@ -92,9 +92,15 @@ def mount_if_exists(route: str, subdir: str, name: str):
|
||||
log.debug("Static directory not found, skipping: %s", path)
|
||||
|
||||
|
||||
mount_if_exists("/js", "js", "js")
|
||||
mount_if_exists("/images", "images", "images")
|
||||
mount_if_exists("/css", "css", "css")
|
||||
mount_if_exists("/js", "dist/js", "js")
|
||||
mount_if_exists("/images", "dist/images", "images")
|
||||
mount_if_exists("/css", "dist/css", "css")
|
||||
|
||||
# Mount Vite build assets (JS bundles, hashed chunks)
|
||||
DIST_ASSETS = os.path.join(FRONTEND_DIR, "dist", "assets")
|
||||
if os.path.isdir(DIST_ASSETS):
|
||||
app.mount("/assets", StaticFiles(directory=DIST_ASSETS), name="assets")
|
||||
log.info("Mounted Vite assets -> %s", DIST_ASSETS)
|
||||
|
||||
UPLOAD_DIR = os.path.abspath(os.path.join(FRONTEND_DIR, "..", "uploads"))
|
||||
if not os.path.exists(UPLOAD_DIR):
|
||||
@@ -103,25 +109,14 @@ if not os.path.exists(UPLOAD_DIR):
|
||||
log.info("FRONTEND_DIR resolved to: %s", FRONTEND_DIR)
|
||||
log.info("CSS dir exists: %s", os.path.isdir(os.path.join(FRONTEND_DIR, "css")))
|
||||
|
||||
DIST_DIR = os.path.join(FRONTEND_DIR, "dist")
|
||||
SPA_INDEX = os.path.join(DIST_DIR, "index.html")
|
||||
|
||||
from fastapi.templating import Jinja2Templates
|
||||
|
||||
templates = Jinja2Templates(directory=FRONTEND_DIR)
|
||||
|
||||
def serve_frontend_file(request: Request, filename: str):
|
||||
full = os.path.join(FRONTEND_DIR, filename)
|
||||
if os.path.isfile(full):
|
||||
return templates.TemplateResponse(
|
||||
name=filename,
|
||||
context={"request": request},
|
||||
headers={
|
||||
"Cache-Control": "no-store, no-cache, must-revalidate",
|
||||
"Pragma": "no-cache",
|
||||
"Expires": "0",
|
||||
},
|
||||
)
|
||||
log.warning("Frontend file not found: %s", full)
|
||||
raise HTTPException(status_code=404, detail="Page not found")
|
||||
# Mount the Vite dist folder for hashed static assets not already mounted above
|
||||
# (favicon, icons.svg, etc.)
|
||||
if os.path.isdir(DIST_DIR):
|
||||
# Serve root-level static assets that Vite places at dist/
|
||||
app.mount("/dist", StaticFiles(directory=DIST_DIR), name="dist_root")
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
@@ -141,57 +136,19 @@ def logout():
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Frontend page routes
|
||||
# SPA catch-all — serve index.html for every non-API GET route
|
||||
# so React Router handles client-side navigation on direct URL access
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
@app.get("/", tags=["frontend"])
|
||||
def home(request: Request): return serve_frontend_file(request, "home.html")
|
||||
|
||||
@app.get("/home", tags=["frontend"])#route to home page
|
||||
def home_page(request: Request): return serve_frontend_file(request, "home.html")
|
||||
|
||||
@app.get("/login", tags=["frontend"]) #route to login page
|
||||
def login_page(request: Request): return serve_frontend_file(request, "login.html")
|
||||
|
||||
@app.get("/signup", tags=["frontend"]) #route to signup page
|
||||
def signup_page(request: Request): return serve_frontend_file(request, "signup.html")
|
||||
|
||||
@app.get("/dashboard", tags=["frontend"])
|
||||
def dashboard_page(request: Request): return serve_frontend_file(request, "dashboard.html") #route to dashboard page
|
||||
|
||||
@app.get("/admin-dashboard", tags=["frontend"])
|
||||
def admin_dashboard_page(request: Request): return serve_frontend_file(request, "admin-dashboard.html") #route to admin dashboard page
|
||||
|
||||
@app.get("/admin-user-detail", tags=["frontend"])
|
||||
def admin_user_detail(request: Request): return serve_frontend_file(request, "admin-user-detail.html") #route to admin-user-detail page
|
||||
|
||||
@app.get("/upload-personal", tags=["frontend"])
|
||||
def upload_personal(request: Request): return serve_frontend_file(request, "upload-personal.html") #route to upload-personal
|
||||
|
||||
@app.get("/upload-business", tags=["frontend"])
|
||||
def upload_business(request: Request): return serve_frontend_file(request, "upload-business.html") #route to upload-business
|
||||
|
||||
@app.get("/contact", tags=["frontend"])
|
||||
def contact_page(request: Request): return serve_frontend_file(request, "contact.html") #route to contact page
|
||||
|
||||
@app.get("/services", tags=["frontend"])
|
||||
def services_page(request: Request): return serve_frontend_file(request, "services.html") #route to service page
|
||||
|
||||
@app.get("/about-us", tags=["frontend"])
|
||||
def about_us_page(request: Request): return serve_frontend_file(request, "about-us.html") # route to about-us page
|
||||
|
||||
|
||||
@app.get("/forgot-password", tags=["frontend"])
|
||||
def forgot_password_page(request: Request): return serve_frontend_file(request, "forgot-password.html")
|
||||
|
||||
@app.get("/profile", tags=["frontend"])
|
||||
def profile_page(request: Request): return serve_frontend_file(request, "profile.html") #route to forgot-password page
|
||||
|
||||
@app.get("/reset-password", tags=["frontend"])
|
||||
def reset_password_page(request: Request): return serve_frontend_file(request, "reset-password.html") #route to reset-password page
|
||||
|
||||
@app.get("/verify-email", tags=["frontend"])
|
||||
def verify_email_page(request: Request): return serve_frontend_file(request, "verify-email.html")# route to verify-email page
|
||||
|
||||
@app.get("/resend-verification", tags=["frontend"]) # route to resend-verification page
|
||||
def resend_verification_page(request: Request): return serve_frontend_file(request, "resend-verification.html")
|
||||
@app.get("/{full_path:path}", tags=["frontend"])
|
||||
def spa_fallback(full_path: str):
|
||||
if os.path.isfile(SPA_INDEX):
|
||||
return FileResponse(
|
||||
SPA_INDEX,
|
||||
headers={
|
||||
"Cache-Control": "no-store, no-cache, must-revalidate",
|
||||
"Pragma": "no-cache",
|
||||
"Expires": "0",
|
||||
},
|
||||
)
|
||||
raise HTTPException(status_code=404, detail="Frontend not built. Run 'npm run build' in /frontend.")
|
||||
|
||||
@@ -7,6 +7,7 @@ from sqlalchemy import (
|
||||
Index,
|
||||
Integer,
|
||||
String,
|
||||
JSON,
|
||||
UniqueConstraint,
|
||||
func,
|
||||
)
|
||||
@@ -61,6 +62,7 @@ class PersonalDocument(Base):
|
||||
review_status = Column(String(20), default="pending", nullable=False)
|
||||
review_note = Column(String(500), nullable=True)
|
||||
tax_year = Column(Integer, default=2025, nullable=False)
|
||||
extracted_data = Column(JSON, nullable=True)
|
||||
|
||||
user = relationship("User")
|
||||
|
||||
@@ -87,6 +89,7 @@ class BusinessDocument(Base):
|
||||
review_status = Column(String(20), default="pending", nullable=False)
|
||||
review_note = Column(String(500), nullable=True)
|
||||
tax_year = Column(Integer, default=2025, nullable=False)
|
||||
extracted_data = Column(JSON, nullable=True)
|
||||
|
||||
user = relationship("User")
|
||||
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import logging
|
||||
from fastapi import APIRouter, Depends
|
||||
from datetime import datetime, date, timedelta
|
||||
from fastapi import APIRouter, Depends, Request, Query
|
||||
from app.limiter import limiter
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import func, or_
|
||||
import os
|
||||
import requests
|
||||
from pydantic import BaseModel
|
||||
from fastapi import HTTPException
|
||||
from app.models import PersonalDocument, BusinessDocument, User
|
||||
from app.models import PersonalDocument, BusinessDocument, User, AuditLog
|
||||
from app.db import get_db
|
||||
from app.auth.security import get_current_user, require_admin
|
||||
|
||||
@@ -14,59 +17,43 @@ logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/api/chatbot", tags=["chatbot"])
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# User: doc status
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
@router.get("/doc-status")
|
||||
def get_doc_status(
|
||||
db: Session = Depends(get_db),
|
||||
current_user=Depends(get_current_user),
|
||||
):
|
||||
"""Return a consolidated summary of the user's document statuses."""
|
||||
|
||||
personal = (
|
||||
db.query(PersonalDocument)
|
||||
.filter(
|
||||
PersonalDocument.user_id == current_user.id,
|
||||
PersonalDocument.deleted_at == None,
|
||||
)
|
||||
.filter(PersonalDocument.user_id == current_user.id, PersonalDocument.deleted_at == None)
|
||||
.order_by(PersonalDocument.tax_year.desc(), PersonalDocument.uploaded_at.desc())
|
||||
.all()
|
||||
)
|
||||
|
||||
business = (
|
||||
db.query(BusinessDocument)
|
||||
.filter(
|
||||
BusinessDocument.user_id == current_user.id,
|
||||
BusinessDocument.deleted_at == None,
|
||||
)
|
||||
.filter(BusinessDocument.user_id == current_user.id, BusinessDocument.deleted_at == None)
|
||||
.order_by(BusinessDocument.tax_year.desc(), BusinessDocument.uploaded_at.desc())
|
||||
.all()
|
||||
)
|
||||
|
||||
personal_list = [
|
||||
{
|
||||
"doc_type": d.doc_type,
|
||||
"status": d.review_status,
|
||||
"note": d.review_note,
|
||||
"tax_year": d.tax_year,
|
||||
"filename": d.filename,
|
||||
}
|
||||
{"doc_type": d.doc_type, "status": d.review_status, "note": d.review_note,
|
||||
"tax_year": d.tax_year, "filename": d.filename}
|
||||
for d in personal
|
||||
]
|
||||
|
||||
business_list = [
|
||||
{
|
||||
"business_type": d.business_type,
|
||||
"status": d.review_status,
|
||||
"note": d.review_note,
|
||||
"tax_year": d.tax_year,
|
||||
"filename": d.filename,
|
||||
}
|
||||
{"business_type": d.business_type, "status": d.review_status, "note": d.review_note,
|
||||
"tax_year": d.tax_year, "filename": d.filename}
|
||||
for d in business
|
||||
]
|
||||
|
||||
all_docs = personal_list + business_list
|
||||
summary = {
|
||||
"total": len(all_docs),
|
||||
"pending": sum(1 for d in all_docs if d["status"] == "pending"),
|
||||
"total": len(all_docs),
|
||||
"pending": sum(1 for d in all_docs if d["status"] == "pending"),
|
||||
"approved": sum(1 for d in all_docs if d["status"] == "approved"),
|
||||
"rejected": sum(1 for d in all_docs if d["status"] == "rejected"),
|
||||
}
|
||||
@@ -76,67 +63,163 @@ def get_doc_status(
|
||||
msg_lines.append("You have not uploaded any documents yet.")
|
||||
else:
|
||||
msg_lines.append(f"You have uploaded <b>{summary['total']}</b> documents in total.")
|
||||
if summary["pending"] > 0:
|
||||
if summary["pending"]:
|
||||
msg_lines.append(f"<br>• <b>{summary['pending']}</b> pending review.")
|
||||
if summary["approved"] > 0:
|
||||
if summary["approved"]:
|
||||
msg_lines.append(f"<br>• <span style='color:var(--success)'><b>{summary['approved']}</b> approved.</span>")
|
||||
if summary["rejected"] > 0:
|
||||
if summary["rejected"]:
|
||||
msg_lines.append(f"<br>• <span style='color:var(--error)'><b>{summary['rejected']}</b> rejected.</span> Please check the upload pages for notes.")
|
||||
|
||||
return {
|
||||
"personal": personal_list,
|
||||
"business": business_list,
|
||||
"summary": summary,
|
||||
"message": "".join(msg_lines),
|
||||
}
|
||||
return {"personal": personal_list, "business": business_list, "summary": summary,
|
||||
"message": "".join(msg_lines)}
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Admin: system overview stats
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
@router.get("/admin-status")
|
||||
def get_admin_status(
|
||||
db: Session = Depends(get_db),
|
||||
current_user=Depends(get_current_user),
|
||||
_=Depends(require_admin),
|
||||
):
|
||||
"""Return system-wide stats for the super admin chatbot."""
|
||||
total_users = db.query(User).count()
|
||||
"""Return system-wide stats for the admin chatbot."""
|
||||
today_start = datetime.combine(date.today(), datetime.min.time())
|
||||
|
||||
total_users = db.query(User).count()
|
||||
new_users_today = db.query(User).filter(User.created_at >= today_start).count()
|
||||
|
||||
pending_personal = (
|
||||
db.query(PersonalDocument)
|
||||
.filter(
|
||||
PersonalDocument.review_status == "pending",
|
||||
PersonalDocument.deleted_at == None,
|
||||
)
|
||||
.filter(PersonalDocument.review_status == "pending", PersonalDocument.deleted_at == None)
|
||||
.count()
|
||||
)
|
||||
pending_business = (
|
||||
db.query(BusinessDocument)
|
||||
.filter(BusinessDocument.review_status == "pending", BusinessDocument.deleted_at == None)
|
||||
.count()
|
||||
)
|
||||
|
||||
pending_business = (
|
||||
db.query(BusinessDocument)
|
||||
.filter(
|
||||
BusinessDocument.review_status == "pending",
|
||||
BusinessDocument.deleted_at == None,
|
||||
)
|
||||
.count()
|
||||
# Most recent 10 uploads across both tables
|
||||
recent_personal = (
|
||||
db.query(PersonalDocument)
|
||||
.filter(PersonalDocument.deleted_at == None)
|
||||
.order_by(PersonalDocument.uploaded_at.desc())
|
||||
.limit(10).all()
|
||||
)
|
||||
recent_business = (
|
||||
db.query(BusinessDocument)
|
||||
.filter(BusinessDocument.deleted_at == None)
|
||||
.order_by(BusinessDocument.uploaded_at.desc())
|
||||
.limit(10).all()
|
||||
)
|
||||
|
||||
# Merge and sort to get true top-10 latest
|
||||
recent_uploads = sorted(
|
||||
[{"user_id": d.user_id, "doc": d.doc_type, "type": "personal",
|
||||
"uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_personal] +
|
||||
[{"user_id": d.user_id, "doc": d.business_type, "type": "business",
|
||||
"uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_business],
|
||||
key=lambda x: x["uploaded_at"], reverse=True
|
||||
)[:10]
|
||||
|
||||
# Enrich with user names
|
||||
user_map = {u.id: u for u in db.query(User).filter(User.id.in_([r["user_id"] for r in recent_uploads])).all()}
|
||||
for r in recent_uploads:
|
||||
u = user_map.get(r["user_id"])
|
||||
r["user_name"] = u.name if u else "Unknown"
|
||||
r["user_email"] = u.email if u else "Unknown"
|
||||
r["uploaded_at"] = r["uploaded_at"].strftime("%Y-%m-%d %H:%M") if r["uploaded_at"] else "N/A"
|
||||
|
||||
message = (
|
||||
f"<b>System Overview:</b><br><br>"
|
||||
f"• Total Users: <b>{total_users}</b><br>"
|
||||
f"• Total Users: <b>{total_users}</b> (<b>{new_users_today}</b> joined today)<br>"
|
||||
f"• Pending Personal Docs: <b>{pending_personal}</b><br>"
|
||||
f"• Pending Business Docs: <b>{pending_business}</b><br><br>"
|
||||
)
|
||||
if pending_personal + pending_business > 0:
|
||||
message += f"You have <b>{pending_personal + pending_business}</b> documents awaiting review in the Dashboard."
|
||||
total_pending = pending_personal + pending_business
|
||||
if total_pending > 0:
|
||||
message += f"You have <b>{total_pending}</b> documents awaiting review."
|
||||
else:
|
||||
message += "All documents have been reviewed!"
|
||||
|
||||
return {
|
||||
"total_users": total_users,
|
||||
"total_users": total_users,
|
||||
"new_users_today": new_users_today,
|
||||
"pending_personal": pending_personal,
|
||||
"pending_business": pending_business,
|
||||
"total_pending": pending_personal + pending_business,
|
||||
"message": message,
|
||||
"total_pending": total_pending,
|
||||
"recent_uploads": recent_uploads,
|
||||
"message": message,
|
||||
}
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Admin: rich context for a specific user (activity + docs)
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
@router.get("/admin-user-context")
|
||||
def get_admin_user_context(
|
||||
query: str = Query(..., description="User name or email to search for"),
|
||||
db: Session = Depends(get_db),
|
||||
current_user=Depends(get_current_user),
|
||||
_=Depends(require_admin),
|
||||
):
|
||||
"""Search for a user by name/email and return their full activity context."""
|
||||
q = f"%{query}%"
|
||||
user = (
|
||||
db.query(User)
|
||||
.filter(or_(User.name.ilike(q), User.email.ilike(q)))
|
||||
.first()
|
||||
)
|
||||
if not user:
|
||||
return {"found": False, "message": f"No user found matching '{query}'."}
|
||||
|
||||
# Docs
|
||||
personal = db.query(PersonalDocument).filter(
|
||||
PersonalDocument.user_id == user.id, PersonalDocument.deleted_at == None
|
||||
).order_by(PersonalDocument.uploaded_at.desc()).all()
|
||||
|
||||
business = db.query(BusinessDocument).filter(
|
||||
BusinessDocument.user_id == user.id, BusinessDocument.deleted_at == None
|
||||
).order_by(BusinessDocument.uploaded_at.desc()).all()
|
||||
|
||||
# Audit log (last 20 actions)
|
||||
audit = (
|
||||
db.query(AuditLog)
|
||||
.filter(AuditLog.user_id == user.id)
|
||||
.order_by(AuditLog.created_at.desc())
|
||||
.limit(20).all()
|
||||
)
|
||||
|
||||
return {
|
||||
"found": True,
|
||||
"user": {
|
||||
"id": user.id,
|
||||
"name": user.name,
|
||||
"email": user.email,
|
||||
"role": user.role.value if hasattr(user.role, "value") else str(user.role),
|
||||
"joined": user.created_at.strftime("%Y-%m-%d") if user.created_at else "N/A",
|
||||
"engagement_acknowledged": bool(user.engagement_acknowledged_at),
|
||||
},
|
||||
"documents": {
|
||||
"personal": [{"doc_type": d.doc_type, "status": d.review_status,
|
||||
"tax_year": d.tax_year,
|
||||
"uploaded_at": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "N/A"} for d in personal],
|
||||
"business": [{"business_type": d.business_type, "status": d.review_status,
|
||||
"tax_year": d.tax_year,
|
||||
"uploaded_at": d.uploaded_at.strftime("%Y-%m-%d %H:%M") if d.uploaded_at else "N/A"} for d in business],
|
||||
},
|
||||
"audit_log": [
|
||||
{"action": l.action, "detail": l.detail, "ip": l.ip_address,
|
||||
"at": l.created_at.strftime("%Y-%m-%d %H:%M") if l.created_at else "N/A"}
|
||||
for l in audit
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Shared chat endpoint
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
class ChatMessage(BaseModel):
|
||||
role: str
|
||||
content: str
|
||||
@@ -145,75 +228,139 @@ class ChatMessage(BaseModel):
|
||||
class ChatRequest(BaseModel):
|
||||
messages: list[ChatMessage]
|
||||
|
||||
|
||||
def _build_admin_context(db: Session, current_user) -> str:
|
||||
"""Build a rich real-time context string for the admin system prompt."""
|
||||
status = get_admin_status(db=db, current_user=current_user, _=None)
|
||||
|
||||
ctx = f"=== LIVE SYSTEM DATA (as of {datetime.now().strftime('%Y-%m-%d %H:%M')}) ===\n"
|
||||
ctx += f"Total registered users: {status['total_users']}\n"
|
||||
ctx += f"New users registered TODAY: {status['new_users_today']}\n"
|
||||
ctx += f"Pending personal docs (system-wide): {status['pending_personal']}\n"
|
||||
ctx += f"Pending business docs (system-wide): {status['pending_business']}\n"
|
||||
ctx += f"Total pending docs: {status['total_pending']}\n\n"
|
||||
|
||||
if status["recent_uploads"]:
|
||||
ctx += "=== MOST RECENT DOCUMENT UPLOADS ===\n"
|
||||
for r in status["recent_uploads"]:
|
||||
ctx += (f"- {r['user_name']} ({r['user_email']}) uploaded a "
|
||||
f"{r['type']} doc '{r['doc']}' on {r['uploaded_at']} "
|
||||
f"[status: {r['status']}]\n")
|
||||
return ctx
|
||||
|
||||
|
||||
@router.post("/ask")
|
||||
@limiter.limit("5/minute")
|
||||
def ask_chatbot(
|
||||
request: Request,
|
||||
req: ChatRequest,
|
||||
current_user=Depends(get_current_user)
|
||||
current_user=Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Send a message to OpenRouter AI."""
|
||||
api_key = os.environ.get("OPENROUTER_API_KEY")
|
||||
if not api_key:
|
||||
raise HTTPException(status_code=500, detail="OpenRouter API key not configured")
|
||||
|
||||
is_admin = current_user.role in ("admin", "super_admin")
|
||||
|
||||
system_prompt = ""
|
||||
if is_admin:
|
||||
context = _build_admin_context(db, current_user)
|
||||
|
||||
# Check if the latest user message references a specific user — if so, fetch their data
|
||||
last_user_msg = next((m.content for m in reversed(req.messages) if m.role == "user"), "")
|
||||
user_context_addon = ""
|
||||
if any(kw in last_user_msg.lower() for kw in ["user", "who", "activity", "uploaded", "registered", "recent"]):
|
||||
# Try to find a name/email in the message
|
||||
words = last_user_msg.replace(",", " ").replace("?", " ").split()
|
||||
for word in words:
|
||||
if "@" in word or len(word) > 4:
|
||||
result = get_admin_user_context(query=word, db=db, current_user=current_user, _=None)
|
||||
if result.get("found"):
|
||||
u = result["user"]
|
||||
docs = result["documents"]
|
||||
audit = result["audit_log"]
|
||||
user_context_addon = f"\n\n=== USER DETAIL: {u['name']} ({u['email']}) ===\n"
|
||||
user_context_addon += f"Role: {u['role']} | Joined: {u['joined']} | Engagement acknowledged: {u['engagement_acknowledged']}\n"
|
||||
if docs["personal"]:
|
||||
user_context_addon += "Personal docs: " + "; ".join(
|
||||
f"{d['doc_type']} ({d['tax_year']}) [{d['status']}] uploaded {d['uploaded_at']}"
|
||||
for d in docs["personal"]) + "\n"
|
||||
if docs["business"]:
|
||||
user_context_addon += "Business docs: " + "; ".join(
|
||||
f"{d['business_type']} ({d['tax_year']}) [{d['status']}] uploaded {d['uploaded_at']}"
|
||||
for d in docs["business"]) + "\n"
|
||||
if audit:
|
||||
user_context_addon += "Recent activity:\n" + "\n".join(
|
||||
f" [{a['at']}] {a['action']} — {a['detail'] or ''} (IP: {a['ip'] or 'N/A'})"
|
||||
for a in audit[:10]) + "\n"
|
||||
break
|
||||
|
||||
system_prompt = (
|
||||
"You are the BookKeepPro Admin Assistant. Your ONLY job is to help admins with this specific application's internal processes. "
|
||||
"IMPORTANT: Do NOT make up URLs, generic advice, or flows. Answer ONLY based on this application's actual flow:\n"
|
||||
"- How to view users: On the Admin Dashboard, click any user in the table to go to their Admin User Detail page.\n"
|
||||
"- How to review/approve docs: On the Admin User Detail page, you will see their uploaded documents. Click a document to download/view it, change its status to 'Approved' or 'Rejected', add an optional review note, and click 'Submit Review'.\n"
|
||||
"- If a doc is rejected: The user is notified and must re-upload it.\n"
|
||||
"Rule: You must ONLY answer questions related to system administration, BookKeepPro, accounting, or taxes. If the admin asks about anything else, politely decline."
|
||||
"You are the BookKeepPro Admin Assistant — a knowledgeable, concise AI that has live access to the system's data.\n\n"
|
||||
"CAPABILITIES:\n"
|
||||
"- You can answer questions about which users uploaded documents and when.\n"
|
||||
"- You can report how many new users registered today or on any date.\n"
|
||||
"- You can show recent activity and document history for any specific user.\n"
|
||||
"- You can answer questions about document review status system-wide.\n\n"
|
||||
"RULES:\n"
|
||||
"- Only answer questions related to BookKeepPro administration, accounting, or taxes.\n"
|
||||
"- Use the live data below to answer. Do NOT make up user names, counts, or dates.\n"
|
||||
"- Be concise and direct. Format answers clearly.\n\n"
|
||||
f"{context}{user_context_addon}"
|
||||
)
|
||||
else:
|
||||
doc_status = get_doc_status(db=db, current_user=current_user)
|
||||
summary = doc_status["summary"]
|
||||
context = f"Total Documents: {summary['total']}\nPending: {summary['pending']}\nApproved: {summary['approved']}\nRejected: {summary['rejected']}\n"
|
||||
|
||||
if doc_status["personal"]:
|
||||
context += "\nPersonal Documents:\n"
|
||||
for d in doc_status["personal"]:
|
||||
note = f" — Admin note: {d['note']}" if d['note'] else ""
|
||||
context += f" • {d['doc_type']} ({d['tax_year']}): {d['status']}{note}\n"
|
||||
if doc_status["business"]:
|
||||
context += "\nBusiness Documents:\n"
|
||||
for d in doc_status["business"]:
|
||||
note = f" — Admin note: {d['note']}" if d['note'] else ""
|
||||
context += f" • {d['business_type']} ({d['tax_year']}): {d['status']}{note}\n"
|
||||
|
||||
system_prompt = (
|
||||
"You are the BookKeepPro Assistant. Your ONLY job is to help users navigate this specific application's features and answer basic accounting/tax questions. "
|
||||
"IMPORTANT: Do NOT make up URLs (like portal.bookkeeppro.com) or generic advice. Answer ONLY based on this application's actual flow:\n"
|
||||
"- How to upload documents: On your Dashboard, find the 'Required Documents' section. Click on a document slot (e.g., Personal or Business) to go to the Upload page. Drag and drop your file (PDF, JPG, PNG, DOCX) or click to browse, then click 'Upload Document'.\n"
|
||||
"- How to check doc status: Look at your Dashboard under 'Required Documents'. It will show 'Pending' (waiting for admin), 'Approved', or 'Rejected'.\n"
|
||||
"- If rejected: Click the rejected document slot again to see the admin's note and upload a new version.\n"
|
||||
"Rule: You must ONLY answer questions related to BookKeepPro, accounting, or taxes. If the user asks about anything else, politely decline."
|
||||
"You are the BookKeepPro Assistant. Help users with this application and basic accounting/tax questions.\n\n"
|
||||
"APPLICATION FLOW:\n"
|
||||
"- Upload documents: Dashboard → Personal Upload or Business Upload page → drag & drop or click to browse.\n"
|
||||
"- Check status: Documents show Pending (waiting for admin), Approved, or Rejected.\n"
|
||||
"- If rejected: see the admin's note on the upload page and re-upload a corrected version.\n"
|
||||
"- Profile: update your name, phone, or password on the Profile page.\n\n"
|
||||
"RULES:\n"
|
||||
"- Only answer questions about BookKeepPro, accounting, or taxes.\n"
|
||||
"- Use the live data below to answer questions about the user's documents.\n\n"
|
||||
f"=== LIVE DATA for {current_user.name or current_user.email} ===\n{context}"
|
||||
)
|
||||
|
||||
messages = [{"role": "system", "content": system_prompt}]
|
||||
|
||||
for m in req.messages:
|
||||
msg = {"role": m.role, "content": m.content}
|
||||
if m.reasoning_details:
|
||||
msg["reasoning_details"] = m.reasoning_details
|
||||
messages.append(msg)
|
||||
messages.append({"role": m.role, "content": m.content})
|
||||
|
||||
try:
|
||||
response = requests.post(
|
||||
url="https://openrouter.ai/api/v1/chat/completions",
|
||||
headers={
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
json={
|
||||
"model": "nvidia/nemotron-3-super-120b-a12b:free",
|
||||
"messages": messages,
|
||||
"reasoning": {"enabled": True}
|
||||
},
|
||||
timeout=30
|
||||
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
|
||||
json={"model": "meta-llama/llama-3.3-70b-instruct", "messages": messages},
|
||||
timeout=30,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
|
||||
if "error" in data:
|
||||
logger.error(f"OpenRouter returned an error payload: {data['error']}")
|
||||
raise HTTPException(status_code=502, detail="AI Service is currently overloaded. Please try again.")
|
||||
|
||||
logger.error(f"OpenRouter error: {data['error']}")
|
||||
raise HTTPException(status_code=502, detail="AI service overloaded. Please try again.")
|
||||
if "choices" not in data:
|
||||
logger.error(f"OpenRouter returned unexpected payload: {data}")
|
||||
raise HTTPException(status_code=502, detail="Unexpected response from AI service. Please try again.")
|
||||
|
||||
return data['choices'][0]['message']
|
||||
|
||||
raise HTTPException(status_code=502, detail="Unexpected AI response. Please try again.")
|
||||
|
||||
return data["choices"][0]["message"]
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"OpenRouter API error: {str(e)}")
|
||||
logger.error(f"OpenRouter API error: {e}")
|
||||
raise HTTPException(status_code=500, detail="Failed to connect to AI service")
|
||||
|
||||
@@ -15,11 +15,14 @@ from jose import jwt, JWTError
|
||||
from datetime import timedelta
|
||||
|
||||
from app.models import AdminDocument, PersonalDocument, BusinessDocument, User, UserRole
|
||||
from app.db import get_db
|
||||
from app.db import get_db, SessionLocal
|
||||
import app.crud as crud
|
||||
from app.auth.security import get_current_user, require_admin, SECRET_KEY, ALGORITHM
|
||||
from app.utils.emailer import send_email
|
||||
from app.utils.ai import extract_document_data
|
||||
from app.schemas import UploadCompleteNotify, ReviewStatusUpdate
|
||||
from app.limiter import limiter
|
||||
from fastapi import Request
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -35,6 +38,26 @@ BASE_DIR = Path(__file__).resolve().parents[4]
|
||||
UPLOAD_DIR = BASE_DIR / "uploads"
|
||||
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def process_ai_extraction(table: str, doc_id: int, file_path: str, doc_type: str):
|
||||
extracted = extract_document_data(file_path, doc_type)
|
||||
if extracted is None:
|
||||
return
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
if table == "personal":
|
||||
doc = db.query(PersonalDocument).filter_by(id=doc_id).first()
|
||||
else:
|
||||
doc = db.query(BusinessDocument).filter_by(id=doc_id).first()
|
||||
|
||||
if doc:
|
||||
doc.extracted_data = extracted
|
||||
db.commit()
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to update DB with AI extraction: {e}")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
async def upload_to_storage(file: UploadFile) -> str:
|
||||
"""Upload to local disk. Returns the filename (storage_key)."""
|
||||
await file.seek(0)
|
||||
@@ -53,6 +76,8 @@ async def upload_to_storage(file: UploadFile) -> str:
|
||||
"image/webp",
|
||||
"application/msword",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
"application/vnd.ms-excel",
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
}
|
||||
|
||||
kind = filetype.guess(contents)
|
||||
@@ -60,15 +85,15 @@ async def upload_to_storage(file: UploadFile) -> str:
|
||||
|
||||
ext = os.path.splitext(file.filename or "file")[1].lower()
|
||||
|
||||
# Fallback for legacy .doc and inconsistent .docx sniffing
|
||||
# Fallback for legacy .doc, .xls, and inconsistent .docx/.xlsx sniffing (which are just zip files)
|
||||
if sniffed_mime is None or sniffed_mime == "application/zip":
|
||||
if ext in [".doc", ".docx"] and file.content_type in ALLOWED_TYPES:
|
||||
if ext in [".doc", ".docx", ".xls", ".xlsx"] and file.content_type in ALLOWED_TYPES:
|
||||
sniffed_mime = file.content_type
|
||||
|
||||
if sniffed_mime not in ALLOWED_TYPES:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"File type not allowed or could not be verified. Allowed: PDF, JPG, PNG, WEBP, DOC, DOCX."
|
||||
detail=f"File type not allowed or could not be verified. Allowed: PDF, JPG, PNG, WEBP, DOC, DOCX, XLS, XLSX."
|
||||
)
|
||||
|
||||
ext = os.path.splitext(file.filename or "file")[1].lower()
|
||||
@@ -345,6 +370,9 @@ async def upload_personal_document(
|
||||
db: Session = Depends(get_db),
|
||||
current_user=Depends(get_current_user),
|
||||
):
|
||||
if not current_user.engagement_acknowledged_at:
|
||||
raise HTTPException(status_code=403, detail="You must acknowledge the engagement letter before uploading.")
|
||||
|
||||
logger.info(f"User {current_user.id} uploading personal document: {file.filename}")
|
||||
storage_key = await upload_to_storage(file)
|
||||
|
||||
@@ -380,6 +408,14 @@ async def upload_personal_document(
|
||||
body=f"<p><strong>{current_user.email}</strong> uploaded a personal document: <strong>{file.filename}</strong> ({doc_type}).</p>",
|
||||
)
|
||||
|
||||
background.add_task(
|
||||
process_ai_extraction,
|
||||
"personal",
|
||||
record.id,
|
||||
str(UPLOAD_DIR / storage_key),
|
||||
doc_type
|
||||
)
|
||||
|
||||
return {
|
||||
"id": record.id,
|
||||
"filename": record.filename,
|
||||
@@ -407,8 +443,8 @@ def delete_personal_document(
|
||||
if not doc:
|
||||
raise HTTPException(status_code=404, detail="Document not found")
|
||||
|
||||
logger.info(f"User {current_user.id} deleting personal document {doc_id}")
|
||||
delete_from_storage(doc.storage_key)
|
||||
logger.info(f"User {current_user.id} deleting personal document {doc_id} (soft delete)")
|
||||
# Soft delete (Option B): Keep file in storage, only mark as deleted in DB
|
||||
doc.deleted_at = datetime.utcnow()
|
||||
db.commit()
|
||||
crud.log_action(db, "delete_personal", user_id=current_user.id, target=f"personal_doc:{doc_id}")
|
||||
@@ -437,6 +473,7 @@ def list_business_documents(
|
||||
return [
|
||||
{
|
||||
"id": d.id,
|
||||
"doc_type": d.business_type,
|
||||
"business_type": d.business_type,
|
||||
"filename": d.filename,
|
||||
"storage_key": d.storage_key,
|
||||
@@ -458,6 +495,9 @@ async def upload_business_document(
|
||||
db: Session = Depends(get_db),
|
||||
current_user=Depends(get_current_user),
|
||||
):
|
||||
if not current_user.engagement_acknowledged_at:
|
||||
raise HTTPException(status_code=403, detail="You must acknowledge the engagement letter before uploading.")
|
||||
|
||||
logger.info(f"User {current_user.id} uploading business document: {file.filename}")
|
||||
storage_key = await upload_to_storage(file)
|
||||
|
||||
@@ -491,6 +531,14 @@ async def upload_business_document(
|
||||
subject="New Business Document Uploaded — BookKeepro",
|
||||
body=f"<p><strong>{current_user.email}</strong> uploaded a business document: <strong>{file.filename}</strong> ({doc_type}).</p>",
|
||||
)
|
||||
|
||||
background.add_task(
|
||||
process_ai_extraction,
|
||||
"business",
|
||||
record.id,
|
||||
str(UPLOAD_DIR / storage_key),
|
||||
doc_type
|
||||
)
|
||||
|
||||
return {
|
||||
"id": record.id,
|
||||
@@ -513,8 +561,8 @@ def delete_business_document(
|
||||
if doc.user_id != current_user.id:
|
||||
raise HTTPException(status_code=403, detail="Not authorized")
|
||||
|
||||
logger.info(f"User {current_user.id} deleting business document {doc_id}")
|
||||
delete_from_storage(doc.storage_key)
|
||||
logger.info(f"User {current_user.id} deleting business document {doc_id} (soft delete)")
|
||||
# Soft delete (Option B): Keep file in storage, only mark as deleted in DB
|
||||
doc.deleted_at = datetime.utcnow()
|
||||
db.commit()
|
||||
crud.log_action(db, "delete_business", user_id=current_user.id, target=f"business_doc:{doc_id}")
|
||||
@@ -626,6 +674,7 @@ def get_user_all_documents(
|
||||
"tax_year": d.tax_year,
|
||||
"review_status": d.review_status,
|
||||
"review_note": d.review_note,
|
||||
"extracted_data": d.extracted_data,
|
||||
}
|
||||
for d in personal_docs
|
||||
] + [
|
||||
@@ -639,6 +688,7 @@ def get_user_all_documents(
|
||||
"tax_year": d.tax_year,
|
||||
"review_status": d.review_status,
|
||||
"review_note": d.review_note,
|
||||
"extracted_data": d.extracted_data,
|
||||
}
|
||||
for d in business_docs
|
||||
]
|
||||
@@ -730,7 +780,9 @@ def delete_user_completely(
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
@router.post("/notify-upload-complete")
|
||||
@limiter.limit("5/minute")
|
||||
async def notify_upload_complete(
|
||||
request: Request,
|
||||
payload: UploadCompleteNotify,
|
||||
background: BackgroundTasks,
|
||||
db: Session = Depends(get_db),
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
import os
|
||||
import json
|
||||
import logging
|
||||
import requests
|
||||
import base64
|
||||
from io import BytesIO
|
||||
from pypdf import PdfReader
|
||||
from PIL import Image
|
||||
import fitz # PyMuPDF — PDF rendering for scanned docs
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Pipeline thresholds
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
MIN_TEXT_CHARS = 50 # Stage 1: native text must have at least this many chars
|
||||
MIN_TESS_WORDS = 30 # Stage 2: Tesseract must return at least this many words
|
||||
RENDER_DPI = 2.5 # PyMuPDF render scale (2.5x ≈ 212 DPI)
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Models
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
MODEL_TEXT = "meta-llama/llama-3.3-70b-instruct" # Stage 1 & 2 — FREE tier
|
||||
MODEL_VISION = "qwen/qwen2.5-vl-72b-instruct" # Stage 3 — best document OCR
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Prompts
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
SYSTEM_PROMPT = (
|
||||
"You are a highly accurate document data extraction AI. "
|
||||
"Extract only what is explicitly present in the document — never invent, guess, or add placeholder fields. "
|
||||
"Respond with a raw JSON object only. No markdown, no explanation, no extra keys."
|
||||
)
|
||||
|
||||
BLANK_FORM_PROMPT = (
|
||||
"This appears to be an unfilled form or template. "
|
||||
"Return a JSON object with these keys only: "
|
||||
"form_type (name of the form), "
|
||||
"tax_year (year if visible, else null), "
|
||||
"purpose (one sentence describing what this form is for), "
|
||||
"status (always set to 'blank_template'). "
|
||||
"Return ONLY valid JSON, no markdown."
|
||||
)
|
||||
|
||||
|
||||
def _build_user_prompt(doc_type: str) -> str:
|
||||
return (
|
||||
f"Document type hint: {doc_type}\n\n"
|
||||
"You are a precise data extraction AI. Read this document and extract its key information.\n\n"
|
||||
"STRICT RULES:\n"
|
||||
"1. Use field names exactly as they appear in the document "
|
||||
"(e.g. 'PAN Number', 'Date of Birth', 'Employer Name', 'Tax Year').\n"
|
||||
"2. For LEGAL DOCUMENTS, LETTERS, or CONTRACTS: extract key terms — "
|
||||
"services included, responsibilities, fees, tax forms mentioned, deadlines, party names.\n"
|
||||
"3. Extract ONLY fields that have actual content — do NOT add null or empty fields.\n"
|
||||
"4. Dates: format as DD/MM/YYYY. A run-together date like '27082022' → '27/08/2022'.\n"
|
||||
"5. For list fields (services, items, fees) use JSON arrays.\n"
|
||||
"6. Ignore bilingual label noise (Hindi/Devanagari text) — extract English values only.\n"
|
||||
"7. If the document is truly a blank unfilled form with zero data, return {}.\n"
|
||||
"8. Return ONLY a valid JSON object — no markdown, no explanation."
|
||||
)
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Helpers
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
def image_to_base64(pil_image: Image.Image, max_size: int = 2048) -> str:
|
||||
"""Encode a PIL image to a base64 data URI, downscaling if needed."""
|
||||
w, h = pil_image.size
|
||||
if w > max_size or h > max_size:
|
||||
scale = max_size / max(w, h)
|
||||
pil_image = pil_image.resize((int(w * scale), int(h * scale)), Image.Resampling.LANCZOS)
|
||||
logger.debug(f"[Vision] Resized {w}x{h} → {pil_image.size}")
|
||||
|
||||
if pil_image.mode != "RGB":
|
||||
pil_image = pil_image.convert("RGB")
|
||||
|
||||
buf = BytesIO()
|
||||
pil_image.save(buf, format="JPEG", quality=92)
|
||||
return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()
|
||||
|
||||
|
||||
def _render_pdf_page(file_path: str, scale: float = RENDER_DPI) -> Image.Image | None:
|
||||
"""Render the first page of a PDF to a PIL Image using PyMuPDF."""
|
||||
try:
|
||||
pdf_doc = fitz.open(file_path)
|
||||
pix = pdf_doc[0].get_pixmap(
|
||||
matrix=fitz.Matrix(scale, scale),
|
||||
colorspace=fitz.csRGB
|
||||
)
|
||||
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
||||
pdf_doc.close()
|
||||
return img
|
||||
except Exception as e:
|
||||
logger.error(f"[PyMuPDF] Render failed for {file_path}: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def _tesseract_text(pil_image: Image.Image) -> str:
|
||||
"""
|
||||
Run Tesseract OCR on a PIL image.
|
||||
Uses eng+hin for bilingual Indian documents (Aadhaar, PAN, tax forms).
|
||||
Falls back to eng-only if Hindi data not installed.
|
||||
Auto-detects binary on Windows vs Linux/Docker.
|
||||
"""
|
||||
try:
|
||||
import pytesseract
|
||||
import platform
|
||||
|
||||
if platform.system() == "Windows":
|
||||
win_paths = [
|
||||
r"C:\Program Files\Tesseract-OCR\tesseract.exe",
|
||||
r"C:\Users\abhil\AppData\Local\Programs\Tesseract-OCR\tesseract.exe",
|
||||
]
|
||||
for p in win_paths:
|
||||
if os.path.isfile(p):
|
||||
pytesseract.pytesseract.tesseract_cmd = p
|
||||
break
|
||||
|
||||
config = "--psm 6 --oem 3"
|
||||
try:
|
||||
text = pytesseract.image_to_string(pil_image, lang="eng+hin", config=config).strip()
|
||||
logger.debug(f"[Tesseract] eng+hin produced {len(text.split())} words")
|
||||
except Exception:
|
||||
logger.debug("[Tesseract] eng+hin unavailable, using eng only")
|
||||
text = pytesseract.image_to_string(pil_image, lang="eng", config=config).strip()
|
||||
|
||||
return text
|
||||
|
||||
except ImportError:
|
||||
logger.warning("[Tesseract] pytesseract not installed — skipping Stage 2")
|
||||
return ""
|
||||
except Exception as e:
|
||||
logger.warning(f"[Tesseract] OCR failed: {e}")
|
||||
return ""
|
||||
|
||||
|
||||
def _call_openrouter(
|
||||
api_key: str,
|
||||
model: str,
|
||||
user_content: list,
|
||||
original_text: str = "",
|
||||
) -> dict | None:
|
||||
"""
|
||||
POST to OpenRouter and return parsed JSON dict, or None on failure.
|
||||
If the model returns {} (blank/unfilled doc), retries with a metadata
|
||||
prompt so the admin always sees form_type / purpose / tax_year.
|
||||
"""
|
||||
def _post(content):
|
||||
try:
|
||||
response = requests.post(
|
||||
url="https://openrouter.ai/api/v1/chat/completions",
|
||||
headers={
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
json={
|
||||
"model": model,
|
||||
"messages": [
|
||||
{"role": "system", "content": SYSTEM_PROMPT},
|
||||
{"role": "user", "content": content},
|
||||
],
|
||||
"response_format": {"type": "json_object"},
|
||||
},
|
||||
timeout=60,
|
||||
)
|
||||
response.raise_for_status()
|
||||
raw = response.json()["choices"][0]["message"]["content"].strip()
|
||||
for fence in ("```json", "```"):
|
||||
if raw.startswith(fence):
|
||||
raw = raw[len(fence):]
|
||||
if raw.endswith("```"):
|
||||
raw = raw[:-3]
|
||||
return json.loads(raw.strip())
|
||||
except Exception as e:
|
||||
logger.error(f"[OpenRouter] {model} call failed: {e}")
|
||||
return None
|
||||
|
||||
result = _post(user_content)
|
||||
|
||||
# If model returned {} (blank template), retry with metadata-only prompt
|
||||
if result == {} and original_text:
|
||||
logger.info("[AI] Empty result — retrying with blank-form metadata prompt")
|
||||
fallback_content = [{
|
||||
"type": "text",
|
||||
"text": f"{BLANK_FORM_PROMPT}\n\nDocument text:\n{original_text[:3000]}"
|
||||
}]
|
||||
result = _post(fallback_content) or {}
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Main extraction entry point
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
def extract_document_data(file_path: str, doc_type: str) -> dict | None:
|
||||
"""
|
||||
3-stage extraction pipeline:
|
||||
|
||||
Stage 1 — Native text (FREE)
|
||||
pypdf + PyMuPDF pull embedded text from the PDF.
|
||||
>= MIN_TEXT_CHARS → llama-3.3-70b (free tier)
|
||||
|
||||
Stage 2 — Tesseract OCR (FREE, local CPU)
|
||||
PyMuPDF renders page at 2.5x DPI.
|
||||
Tesseract reads with eng+hin for bilingual docs.
|
||||
>= MIN_TESS_WORDS → llama-3.3-70b (free tier)
|
||||
|
||||
Stage 3 — Qwen2.5-VL-72B vision (paid, minimal cost)
|
||||
Sends rendered page image to Qwen via OpenRouter.
|
||||
|
||||
Blank template fallback:
|
||||
If any stage returns {}, a second call extracts
|
||||
form_type / purpose / tax_year / status metadata.
|
||||
"""
|
||||
api_key = os.getenv("OPENROUTER_API_KEY")
|
||||
if not api_key:
|
||||
logger.warning("[AI] OPENROUTER_API_KEY not set — skipping extraction")
|
||||
return None
|
||||
|
||||
is_pdf = file_path.lower().endswith(".pdf")
|
||||
is_image = file_path.lower().endswith((".jpg", ".jpeg", ".png", ".webp"))
|
||||
|
||||
if not (is_pdf or is_image):
|
||||
logger.info(f"[AI] Unsupported file type, skipping: {file_path}")
|
||||
return None
|
||||
|
||||
user_prompt = _build_user_prompt(doc_type)
|
||||
|
||||
try:
|
||||
# ── PDF ───────────────────────────────────────────────────────────────
|
||||
if is_pdf:
|
||||
|
||||
# Stage 1: native text
|
||||
text = ""
|
||||
try:
|
||||
reader = PdfReader(file_path)
|
||||
for page in reader.pages[:3]:
|
||||
t = page.extract_text()
|
||||
if t:
|
||||
text += t + "\n"
|
||||
except Exception as e:
|
||||
logger.warning(f"[Stage1] pypdf failed: {e}")
|
||||
|
||||
# PyMuPDF sometimes recovers text pypdf misses
|
||||
if len(text.strip()) < MIN_TEXT_CHARS:
|
||||
try:
|
||||
doc = fitz.open(file_path)
|
||||
mu = "".join(doc[i].get_text() for i in range(min(3, len(doc))))
|
||||
doc.close()
|
||||
if len(mu.strip()) > len(text.strip()):
|
||||
text = mu
|
||||
except Exception as e:
|
||||
logger.warning(f"[Stage1] PyMuPDF text failed: {e}")
|
||||
|
||||
if len(text.strip()) >= MIN_TEXT_CHARS:
|
||||
logger.info(f"[Stage1] Text PDF ({len(text.strip())} chars) → {MODEL_TEXT}")
|
||||
content = [{"type": "text", "text": f"{user_prompt}\n\nDocument text:\n{text.strip()}"}]
|
||||
return _call_openrouter(api_key, MODEL_TEXT, content, original_text=text.strip())
|
||||
|
||||
# Stage 2 & 3 need rendered image
|
||||
rendered = _render_pdf_page(file_path)
|
||||
if rendered is None:
|
||||
return None
|
||||
|
||||
# Stage 2: Tesseract
|
||||
tess_text = _tesseract_text(rendered)
|
||||
word_count = len(tess_text.split())
|
||||
|
||||
if word_count >= MIN_TESS_WORDS:
|
||||
logger.info(f"[Stage2] Tesseract {word_count} words → {MODEL_TEXT} (free)")
|
||||
content = [{"type": "text", "text": f"{user_prompt}\n\nDocument text (OCR):\n{tess_text}"}]
|
||||
result = _call_openrouter(api_key, MODEL_TEXT, content, original_text=tess_text)
|
||||
if result is not None:
|
||||
return result
|
||||
logger.warning("[Stage2] Text model failed — falling through to Stage 3")
|
||||
else:
|
||||
logger.info(f"[Stage2] Tesseract only {word_count} words (threshold {MIN_TESS_WORDS}) → Stage 3")
|
||||
|
||||
# Stage 3: vision model
|
||||
logger.info(f"[Stage3] Vision model: {MODEL_VISION}")
|
||||
content = [
|
||||
{"type": "text", "text": user_prompt},
|
||||
{"type": "image_url", "image_url": {"url": image_to_base64(rendered)}},
|
||||
]
|
||||
return _call_openrouter(api_key, MODEL_VISION, content)
|
||||
|
||||
# ── Image ─────────────────────────────────────────────────────────────
|
||||
elif is_image:
|
||||
img = Image.open(file_path)
|
||||
|
||||
tess_text = _tesseract_text(img)
|
||||
word_count = len(tess_text.split())
|
||||
|
||||
if word_count >= MIN_TESS_WORDS:
|
||||
logger.info(f"[Stage2-img] Tesseract {word_count} words → {MODEL_TEXT} (free)")
|
||||
content = [{"type": "text", "text": f"{user_prompt}\n\nDocument text (OCR):\n{tess_text}"}]
|
||||
result = _call_openrouter(api_key, MODEL_TEXT, content, original_text=tess_text)
|
||||
if result is not None:
|
||||
return result
|
||||
logger.warning("[Stage2-img] Text model failed — Stage 3")
|
||||
else:
|
||||
logger.info(f"[Stage2-img] Tesseract only {word_count} words → Stage 3")
|
||||
|
||||
logger.info(f"[Stage3-img] Vision model: {MODEL_VISION}")
|
||||
content = [
|
||||
{"type": "text", "text": user_prompt},
|
||||
{"type": "image_url", "image_url": {"url": image_to_base64(img)}},
|
||||
]
|
||||
return _call_openrouter(api_key, MODEL_VISION, content)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[AI] Extraction pipeline failed for {file_path}: {e}")
|
||||
return None
|
||||
Reference in New Issue
Block a user