simikkk commited on
Commit
ec90d7f
·
verified ·
1 Parent(s): 517a0cf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +875 -662
app.py CHANGED
@@ -1,723 +1,936 @@
1
  """
2
- app.py -- OmniParse AI main application.
3
-
4
- Architecture:
5
- * Gradio is used purely as a headless API/session backend (Blocks with
6
- visible=False components acting as an RPC bridge).
7
- * The actual UI is a single gr.HTML() block containing hand-written
8
- Tailwind-based HTML/CSS/JS. JS calls into Python by writing into a
9
- hidden gr.Textbox and firing a hidden gr.Button.click().
10
- * Gradio 4.x is built on FastAPI, so we mount the Stripe webhook route
11
- directly on the underlying FastAPI app (needs raw bytes + header
12
- signature verification, which Gradio components can't provide).
13
  """
14
 
15
  import os
 
16
  import json
17
- import base64
18
- import logging
19
 
20
  import gradio as gr
21
 
22
- import auth
23
- import backend
24
- import database as db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- logging.basicConfig(level=logging.INFO)
27
- logger = logging.getLogger("omniparse.app")
 
 
 
 
 
 
 
28
 
29
- APP_TITLE = "OmniParse AI"
 
 
 
 
 
 
 
30
 
31
- PLAN_LIMITS = {
32
- "free": {"invoices": 20, "users": 1, "label": "Free"},
33
- "basic": {"invoices": 200, "users": 1, "label": "Basic"},
34
- "pro": {"invoices": 2000, "users": 3, "label": "Pro"},
35
- "enterprise": {"invoices": float("inf"), "users": float("inf"), "label": "Enterprise"},
36
- }
37
 
38
  # ---------------------------------------------------------------------------
39
- # Shared CSS: hides Gradio chrome, defines tooltips + skeleton loaders.
40
- # ---------------------------------------------------------------------------
41
- BASE_CSS = """
42
- <style>
43
- footer, .gradio-container .footer, #footer { display: none !important; }
44
- .gradio-container { max-width: 100% !important; padding: 0 !important; background: #0b0d12 !important; }
45
- body { margin: 0; font-family: 'Inter', ui-sans-serif, system-ui, sans-serif; }
46
-
47
- /* ---------------- Tooltip ---------------- */
48
- .op-tooltip { position: relative; display: inline-flex; }
49
- .op-tooltip::after {
50
- content: attr(data-tip);
51
- position: absolute;
52
- bottom: 125%; left: 50%; transform: translateX(-50%);
53
- background: #111827; color: #f9fafb; padding: 6px 10px;
54
- border-radius: 6px; font-size: 12px; white-space: nowrap;
55
- opacity: 0; pointer-events: none; transition: opacity 0.15s ease;
56
- box-shadow: 0 4px 14px rgba(0,0,0,0.35);
57
- z-index: 50;
58
- }
59
- .op-tooltip::before {
60
- content: ""; position: absolute; bottom: 118%; left: 50%; transform: translateX(-50%);
61
- border: 5px solid transparent; border-top-color: #111827;
62
- opacity: 0; transition: opacity 0.15s ease; z-index: 50;
63
- }
64
- .op-tooltip:hover::after, .op-tooltip:hover::before { opacity: 1; }
65
 
66
- /* ---------------- Skeleton loaders ---------------- */
67
- @keyframes op-shimmer {
68
- 0% { background-position: -400px 0; }
69
- 100% { background-position: 400px 0; }
70
- }
71
- .op-skel {
72
- background: linear-gradient(90deg, #1a1d27 25%, #232734 37%, #1a1d27 63%);
73
- background-size: 800px 100%;
74
- animation: op-shimmer 1.4s ease-in-out infinite;
75
- border-radius: 8px;
76
- }
77
- .op-skel-row { height: 44px; margin-bottom: 8px; }
78
- .op-skel-text { height: 14px; width: 60%; margin-bottom: 6px; }
79
 
80
- .op-fade-in { animation: op-fade 0.25s ease both; }
81
- @keyframes op-fade { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
82
- </style>
83
- """
84
 
85
  # ---------------------------------------------------------------------------
86
- # Landing page HTML
87
- # ---------------------------------------------------------------------------
88
- LANDING_HTML = f"""
89
- {BASE_CSS}
90
- <script src="https://cdn.tailwindcss.com"></script>
91
- <div id="op-root" class="min-h-screen bg-[#0b0d12] text-gray-100">
92
-
93
- <nav class="flex items-center justify-between px-8 py-5 border-b border-gray-800">
94
- <div class="flex items-center gap-2">
95
- <div class="w-8 h-8 rounded-lg bg-gradient-to-br from-indigo-500 to-cyan-400"></div>
96
- <span class="font-semibold text-lg">{APP_TITLE}</span>
97
- </div>
98
- <div class="flex items-center gap-6 text-sm text-gray-300">
99
- <a href="#pricing" class="hover:text-white">Pricing</a>
100
- <a href="#faq" class="hover:text-white">FAQ</a>
101
- <button onclick="opNavigate('legal')" class="hover:text-white">Legal</button>
102
- <button onclick="opNavigate('login')" class="hover:text-white">Log in</button>
103
- <button onclick="opNavigate('register')"
104
- class="op-tooltip bg-indigo-500 hover:bg-indigo-400 text-white px-4 py-2 rounded-lg font-medium"
105
- data-tip="Start free, no card required">
106
- Get started
107
- </button>
108
- </div>
109
- </nav>
110
-
111
- <header class="text-center px-6 py-24 max-w-4xl mx-auto">
112
- <h1 class="text-5xl font-bold tracking-tight mb-4">Invoice processing in seconds, not hours.</h1>
113
- <p class="text-gray-400 text-lg mb-6">99.2% accuracy &middot; &lt;4s per invoice &middot; 40+ formats</p>
114
- <div class="flex items-center justify-center gap-4">
115
- <button onclick="opNavigate('register')" class="bg-indigo-500 hover:bg-indigo-400 px-6 py-3 rounded-lg font-semibold">Start free</button>
116
- <button onclick="opNavigate('pricing')" class="border border-gray-700 hover:border-gray-500 px-6 py-3 rounded-lg font-semibold">See pricing</button>
117
- </div>
118
- </header>
119
-
120
- <section class="grid grid-cols-1 md:grid-cols-4 gap-6 px-8 max-w-6xl mx-auto pb-24">
121
- <div class="op-tooltip bg-[#12141c] border border-gray-800 rounded-xl p-6" data-tip="Google Vision + pytesseract, cross-checked by an LLM">
122
- <h3 class="font-semibold mb-2">OCR + LLM extraction</h3>
123
- <p class="text-sm text-gray-400">Combines computer vision OCR with large language models for structured field extraction.</p>
124
- </div>
125
- <div class="op-tooltip bg-[#12141c] border border-gray-800 rounded-xl p-6" data-tip="Flags repeated vendor + amount within the same month">
126
- <h3 class="font-semibold mb-2">Duplicate detection</h3>
127
- <p class="text-sm text-gray-400">Automatically flags invoices that match an existing vendor and amount this month.</p>
128
- </div>
129
- <div class="op-tooltip bg-[#12141c] border border-gray-800 rounded-xl p-6" data-tip="Chat with your invoice history, Pro plan and above">
130
- <h3 class="font-semibold mb-2">AI Chat</h3>
131
- <p class="text-sm text-gray-400">Ask questions about your invoice data in plain English.</p>
132
- </div>
133
- <div class="op-tooltip bg-[#12141c] border border-gray-800 rounded-xl p-6" data-tip="Subtotal + tax is checked against the total, tolerance 0.10">
134
- <h3 class="font-semibold mb-2">Cross-field validation</h3>
135
- <p class="text-sm text-gray-400">Automatically verifies that subtotal plus tax reconciles with the stated total.</p>
136
- </div>
137
- </section>
138
-
139
- <section id="pricing" class="px-8 pb-24 max-w-6xl mx-auto">
140
- <h2 class="text-3xl font-bold text-center mb-10">Pricing</h2>
141
- <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
142
-
143
- <div class="bg-[#12141c] border border-gray-800 rounded-xl p-6 flex flex-col">
144
- <h3 class="font-semibold text-lg">Free</h3>
145
- <p class="text-3xl font-bold my-3">$0<span class="text-sm text-gray-500">/mo</span></p>
146
- <ul class="text-sm text-gray-400 space-y-2 flex-1">
147
- <li class="op-tooltip" data-tip="Resets on the 1st of each month">20 invoices/mo</li>
148
- <li>1 user</li>
149
- <li>CSV export</li>
150
- </ul>
151
- <button onclick="opNavigate('register')" class="mt-6 border border-gray-700 hover:border-gray-500 rounded-lg py-2 font-medium">Choose Free</button>
152
- </div>
153
-
154
- <div class="bg-[#12141c] border border-gray-800 rounded-xl p-6 flex flex-col">
155
- <h3 class="font-semibold text-lg">Basic</h3>
156
- <p class="text-3xl font-bold my-3">$29<span class="text-sm text-gray-500">/mo</span></p>
157
- <ul class="text-sm text-gray-400 space-y-2 flex-1">
158
- <li>200 invoices/mo</li>
159
- <li>1 user</li>
160
- <li>JSON/Excel export</li>
161
- </ul>
162
- <button onclick="opCheckout('basic')" class="mt-6 border border-gray-700 hover:border-gray-500 rounded-lg py-2 font-medium">Choose Basic</button>
163
- </div>
164
-
165
- <div class="bg-[#12141c] border-2 border-indigo-500 rounded-xl p-6 flex flex-col relative">
166
- <span class="absolute -top-3 left-1/2 -translate-x-1/2 bg-indigo-500 text-xs px-3 py-1 rounded-full font-semibold">Most popular</span>
167
- <h3 class="font-semibold text-lg">Pro</h3>
168
- <p class="text-3xl font-bold my-3">$129<span class="text-sm text-gray-500">/mo</span></p>
169
- <ul class="text-sm text-gray-400 space-y-2 flex-1">
170
- <li>2000 invoices/mo</li>
171
- <li>3 users</li>
172
- <li class="op-tooltip" data-tip="Programmatic access via api_key">REST API</li>
173
- <li>AI Chat</li>
174
- <li>Duplicate detection</li>
175
- </ul>
176
- <button onclick="opCheckout('pro')" class="mt-6 bg-indigo-500 hover:bg-indigo-400 rounded-lg py-2 font-medium">Choose Pro</button>
177
- </div>
178
-
179
- <div class="bg-[#12141c] border border-gray-800 rounded-xl p-6 flex flex-col">
180
- <h3 class="font-semibold text-lg">Enterprise</h3>
181
- <p class="text-3xl font-bold my-3">$499<span class="text-sm text-gray-500">/mo</span></p>
182
- <ul class="text-sm text-gray-400 space-y-2 flex-1">
183
- <li>Unlimited invoices</li>
184
- <li class="op-tooltip" data-tip="A human reviews low-confidence extractions">Human review UI</li>
185
- <li>SLA</li>
186
- </ul>
187
- <button onclick="opCheckout('enterprise')" class="mt-6 border border-gray-700 hover:border-gray-500 rounded-lg py-2 font-medium">Contact sales</button>
188
- </div>
189
- </div>
190
- </section>
191
-
192
- <section id="faq" class="px-8 pb-24 max-w-3xl mx-auto">
193
- <h2 class="text-3xl font-bold text-center mb-10">Frequently asked questions</h2>
194
- <div id="op-faq-list" class="space-y-3"></div>
195
- </section>
196
- </div>
197
-
198
- <script>
199
- const OP_FAQ = [
200
- ["What file formats are supported?", "OmniParse AI accepts PDF invoices and common image formats (PNG, JPG, WEBP) up to 5MB, covering 40+ regional invoice layouts."],
201
- ["How accurate is the extraction?", "Our OCR + LLM cascade achieves 99.2% field-level accuracy on standard invoice layouts, with automatic flagging of low-confidence results for review."],
202
- ["What happens if a field can't be validated?", "Invoices where the subtotal and tax don't reconcile with the total are marked 'needs review' instead of being silently accepted."],
203
- ["Can I cancel anytime?", "Yes, all paid plans are month-to-month and can be cancelled from your dashboard at any time."],
204
- ["Is my data secure?", "All data is encrypted in transit and at rest, access is enforced via row-level security, and passwords are hashed with bcrypt."]
205
- ];
206
-
207
- function opRenderFaq() {{
208
- const list = document.getElementById('op-faq-list');
209
- if (!list) return;
210
- list.innerHTML = OP_FAQ.map((item, i) => `
211
- <div class="bg-[#12141c] border border-gray-800 rounded-xl overflow-hidden">
212
- <button onclick="opToggleFaq(${{i}})" class="w-full text-left px-5 py-4 flex justify-between items-center">
213
- <span class="font-medium">${{item[0]}}</span>
214
- <span id="op-faq-icon-${{i}}" class="text-gray-500">+</span>
215
- </button>
216
- <div id="op-faq-body-${{i}}" class="hidden px-5 pb-4 text-sm text-gray-400">${{item[1]}}</div>
217
- </div>
218
- `).join('');
219
- }}
220
- function opToggleFaq(i) {{
221
- const body = document.getElementById('op-faq-body-' + i);
222
- const icon = document.getElementById('op-faq-icon-' + i);
223
- const isHidden = body.classList.contains('hidden');
224
- body.classList.toggle('hidden');
225
- icon.textContent = isHidden ? '\u2212' : '+';
226
- }}
227
- opRenderFaq();
228
-
229
- function opNavigate(route) {{
230
- const input = document.querySelector('#op-route-bridge textarea, #op-route-bridge input');
231
- if (!input) return;
232
- input.value = route;
233
- input.dispatchEvent(new Event('input', {{ bubbles: true }}));
234
- document.querySelector('#op-route-trigger button').click();
235
- }}
236
- function opCheckout(plan) {{
237
- const input = document.querySelector('#op-checkout-bridge textarea, #op-checkout-bridge input');
238
- if (!input) return;
239
- input.value = plan;
240
- input.dispatchEvent(new Event('input', {{ bubbles: true }}));
241
- document.querySelector('#op-checkout-trigger button').click();
242
- }}
243
- </script>
244
- """
245
 
246
- LEGAL_HTML = f"""
247
- {BASE_CSS}
248
- <script src="https://cdn.tailwindcss.com"></script>
249
- <div class="min-h-screen bg-[#0b0d12] text-gray-100 px-8 py-16 max-w-3xl mx-auto">
250
- <button onclick="opNavigate('landing')" class="text-sm text-gray-400 hover:text-white mb-8">&larr; Back</button>
251
- <h1 class="text-3xl font-bold mb-6">Terms of Service &amp; Privacy Policy</h1>
252
- <p class="text-gray-400 text-sm mb-4">This is placeholder legal copy for demonstration purposes. Replace with counsel-reviewed
253
- Terms of Service, a Privacy Policy, and a Data Processing Agreement before accepting real customer data.</p>
254
- </div>
255
- <script>
256
- function opNavigate(route) {{
257
- const input = document.querySelector('#op-route-bridge textarea, #op-route-bridge input');
258
- if (!input) return;
259
- input.value = route;
260
- input.dispatchEvent(new Event('input', {{ bubbles: true }}));
261
- document.querySelector('#op-route-trigger button').click();
262
- }}
263
- </script>
264
- """
265
 
266
- AUTH_HTML_TMPL = """
267
- {css}
268
- <script src="https://cdn.tailwindcss.com"></script>
269
- <div class="min-h-screen bg-[#0b0d12] text-gray-100 flex items-center justify-center px-4">
270
- <div class="w-full max-w-sm bg-[#12141c] border border-gray-800 rounded-xl p-8">
271
- <h1 class="text-xl font-bold mb-1">{heading}</h1>
272
- <p class="text-sm text-gray-500 mb-6">{sub}</p>
273
- <div id="op-auth-error" class="hidden text-sm text-red-400 bg-red-950/40 border border-red-900 rounded-lg px-3 py-2 mb-4"></div>
274
- {fields}
275
- <button onclick="{submit_fn}()" class="w-full bg-indigo-500 hover:bg-indigo-400 rounded-lg py-2 font-medium mt-2">{cta}</button>
276
- <p class="text-xs text-gray-500 mt-4 text-center">{footer}</p>
277
- </div>
278
- </div>
279
- <script>
280
- function opNavigate(route) {{
281
- const input = document.querySelector('#op-route-bridge textarea, #op-route-bridge input');
282
- if (!input) return;
283
- input.value = route;
284
- input.dispatchEvent(new Event('input', {{ bubbles: true }}));
285
- document.querySelector('#op-route-trigger button').click();
286
- }}
287
- function opShowError(msg) {{
288
- const el = document.getElementById('op-auth-error');
289
- el.textContent = msg;
290
- el.classList.remove('hidden');
291
- }}
292
- function opSubmitAuth(action) {{
293
- const payload = {{ action }};
294
- document.querySelectorAll('.op-field').forEach(f => payload[f.name] = f.value);
295
- const input = document.querySelector('#op-auth-bridge textarea, #op-auth-bridge input');
296
- input.value = JSON.stringify(payload);
297
- input.dispatchEvent(new Event('input', {{ bubbles: true }}));
298
- document.querySelector('#op-auth-trigger button').click();
299
- }}
300
- function opLogin() {{ opSubmitAuth('login'); }}
301
- function opRegister() {{ opSubmitAuth('register'); }}
302
- function opReset() {{ opSubmitAuth('reset'); }}
303
- </script>
304
- """
 
 
 
 
 
 
 
 
 
305
 
306
 
307
- def render_login_html() -> str:
308
- fields = """
309
- <input class="op-field w-full bg-[#0b0d12] border border-gray-700 rounded-lg px-3 py-2 mb-3 text-sm" name="email" type="email" placeholder="Email">
310
- <input class="op-field w-full bg-[#0b0d12] border border-gray-700 rounded-lg px-3 py-2 mb-3 text-sm" name="password" type="password" placeholder="Password">
311
- """
312
- return AUTH_HTML_TMPL.format(
313
- css=BASE_CSS, heading="Welcome back", sub="Log in to your OmniParse AI account.",
314
- fields=fields, submit_fn="opLogin", cta="Log in",
315
- footer='No account? <button onclick="opNavigate(\'register\')" class="text-indigo-400">Sign up</button>',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
  )
317
 
318
 
319
- def render_register_html() -> str:
320
- fields = """
321
- <input class="op-field w-full bg-[#0b0d12] border border-gray-700 rounded-lg px-3 py-2 mb-3 text-sm" name="name" type="text" placeholder="Full name">
322
- <input class="op-field w-full bg-[#0b0d12] border border-gray-700 rounded-lg px-3 py-2 mb-3 text-sm" name="email" type="email" placeholder="Email">
323
- <input class="op-field w-full bg-[#0b0d12] border border-gray-700 rounded-lg px-3 py-2 mb-3 text-sm" name="password" type="password" placeholder="Password (min. 8 characters)">
324
- """
325
- return AUTH_HTML_TMPL.format(
326
- css=BASE_CSS, heading="Create your account", sub="Start with 20 free invoices a month.",
327
- fields=fields, submit_fn="opRegister", cta="Create account",
328
- footer='Already have an account? <button onclick="opNavigate(\'login\')" class="text-indigo-400">Log in</button>',
329
  )
330
 
331
 
332
- DASHBOARD_HTML_TMPL = """
333
- {css}
334
- <script src="https://cdn.tailwindcss.com"></script>
335
- <div class="min-h-screen bg-[#0b0d12] text-gray-100">
336
- <nav class="flex items-center justify-between px-8 py-4 border-b border-gray-800">
337
- <div class="flex items-center gap-2">
338
- <div class="w-7 h-7 rounded-lg bg-gradient-to-br from-indigo-500 to-cyan-400"></div>
339
- <span class="font-semibold">{app_title}</span>
340
- <span class="ml-2 text-xs bg-indigo-500/20 text-indigo-300 px-2 py-0.5 rounded-full">{plan_label}</span>
341
- </div>
342
- <div class="flex items-center gap-4 text-sm text-gray-300">
343
- <span class="op-tooltip" data-tip="Invoices processed this calendar month">{used}/{limit} used</span>
344
- <button onclick="opLogout()" class="hover:text-white">Log out</button>
345
- </div>
346
- </nav>
347
-
348
- <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 p-8">
349
- <div class="lg:col-span-2 space-y-6">
350
- <div id="op-dropzone"
351
- ondragover="event.preventDefault(); this.classList.add('border-indigo-400');"
352
- ondragleave="this.classList.remove('border-indigo-400');"
353
- ondrop="opHandleDrop(event)"
354
- class="op-tooltip border-2 border-dashed border-gray-700 rounded-xl p-10 text-center cursor-pointer"
355
- data-tip="PDF, PNG or JPG, up to 5MB"
356
- onclick="document.getElementById('op-file-input').click()">
357
- <p class="font-medium">Drop an invoice here, or click to browse</p>
358
- <p class="text-xs text-gray-500 mt-1">PDF, PNG, JPG &middot; max 5MB</p>
359
- <input id="op-file-input" type="file" accept=".pdf,.png,.jpg,.jpeg,.webp" class="hidden" onchange="opHandleFileInput(event)">
360
- </div>
361
-
362
- <div id="op-skeleton-area" class="hidden space-y-2">
363
- <div class="op-skel op-skel-row"></div>
364
- <div class="op-skel op-skel-row"></div>
365
- <div class="op-skel op-skel-row"></div>
366
- </div>
367
-
368
- <div class="bg-[#12141c] border border-gray-800 rounded-xl overflow-hidden">
369
- <table class="w-full text-sm">
370
- <thead class="bg-[#181b25] text-gray-400 text-xs uppercase">
371
- <tr>
372
- <th class="text-left px-4 py-3">Vendor</th>
373
- <th class="text-left px-4 py-3">Invoice #</th>
374
- <th class="text-left px-4 py-3">Date</th>
375
- <th class="text-right px-4 py-3">Total</th>
376
- <th class="text-left px-4 py-3">Status</th>
377
- </tr>
378
- </thead>
379
- <tbody id="op-invoice-rows">{invoice_rows}</tbody>
380
- </table>
381
- </div>
382
- </div>
383
-
384
- <div class="bg-[#12141c] border border-gray-800 rounded-xl p-5 flex flex-col h-[560px]">
385
- <h3 class="font-semibold mb-1 op-tooltip" data-tip="Available on Pro and Enterprise plans">AI Chat</h3>
386
- <div id="op-chat-log" class="flex-1 overflow-y-auto space-y-3 my-3 text-sm">{chat_placeholder}</div>
387
- <div class="flex gap-2">
388
- <input id="op-chat-input" {chat_disabled} class="flex-1 bg-[#0b0d12] border border-gray-700 rounded-lg px-3 py-2 text-sm" placeholder="Ask about your invoices...">
389
- <button onclick="opSendChat()" {chat_disabled} class="bg-indigo-500 hover:bg-indigo-400 disabled:opacity-40 rounded-lg px-4 text-sm font-medium">Send</button>
390
- </div>
391
- </div>
392
- </div>
393
- </div>
394
-
395
- <script>
396
- function opNavigate(route) {{
397
- const input = document.querySelector('#op-route-bridge textarea, #op-route-bridge input');
398
- if (!input) return;
399
- input.value = route;
400
- input.dispatchEvent(new Event('input', {{ bubbles: true }}));
401
- document.querySelector('#op-route-trigger button').click();
402
- }}
403
- function opLogout() {{ opNavigate('logout'); }}
404
-
405
- function opHandleDrop(ev) {{
406
- ev.preventDefault();
407
- ev.currentTarget.classList.remove('border-indigo-400');
408
- const file = ev.dataTransfer.files[0];
409
- if (file) opUploadFile(file);
410
- }}
411
- function opHandleFileInput(ev) {{
412
- const file = ev.target.files[0];
413
- if (file) opUploadFile(file);
414
- }}
415
- function opUploadFile(file) {{
416
- if (file.size > 5 * 1024 * 1024) {{
417
- alert('File exceeds the 5MB limit.');
418
- return;
419
- }}
420
- document.getElementById('op-skeleton-area').classList.remove('hidden');
421
- const reader = new FileReader();
422
- reader.onload = function() {{
423
- const payload = JSON.stringify({{ filename: file.name, data: reader.result }});
424
- const input = document.querySelector('#op-upload-bridge textarea, #op-upload-bridge input');
425
- input.value = payload;
426
- input.dispatchEvent(new Event('input', {{ bubbles: true }}));
427
- document.querySelector('#op-upload-trigger button').click();
428
- }};
429
- reader.readAsDataURL(file);
430
- }}
431
- function opSendChat() {{
432
- const box = document.getElementById('op-chat-input');
433
- const msg = box.value.trim();
434
- if (!msg) return;
435
- box.value = '';
436
- const log = document.getElementById('op-chat-log');
437
- log.innerHTML += `<div class="text-right"><span class="inline-block bg-indigo-500/20 rounded-lg px-3 py-2">${{msg}}</span></div>`;
438
- const input = document.querySelector('#op-chat-bridge textarea, #op-chat-bridge input');
439
- input.value = msg;
440
- input.dispatchEvent(new Event('input', {{ bubbles: true }}));
441
- document.querySelector('#op-chat-trigger button').click();
442
- }}
443
- </script>
444
- """
445
 
446
 
447
- def render_invoice_rows(invoices: list) -> str:
448
- if not invoices:
449
- return '<tr><td colspan="5" class="px-4 py-6 text-center text-gray-500">No invoices processed yet.</td></tr>'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
450
  rows = []
451
  for inv in invoices:
452
  status = inv.get("status", "done")
453
- badge_color = {
454
- "done": "bg-emerald-500/20 text-emerald-300",
455
- "needs_review": "bg-amber-500/20 text-amber-300",
456
- "error": "bg-red-500/20 text-red-300",
457
- "processing": "bg-gray-500/20 text-gray-300",
458
- }.get(status, "bg-gray-500/20 text-gray-300")
459
- dup_flag = ' <span class="text-xs text-amber-400">(dup)</span>' if inv.get("is_duplicate") else ""
460
- rows.append(f"""
461
- <tr class="border-t border-gray-800 op-fade-in">
462
- <td class="px-4 py-3">{inv.get('vendor') or '—'}{dup_flag}</td>
463
- <td class="px-4 py-3">{inv.get('inv_number') or '—'}</td>
464
- <td class="px-4 py-3">{inv.get('inv_date') or '—'}</td>
465
- <td class="px-4 py-3 text-right">{inv.get('total') if inv.get('total') is not None else '—'} {inv.get('currency') or ''}</td>
466
- <td class="px-4 py-3"><span class="text-xs px-2 py-1 rounded-full {badge_color}">{status}</span></td>
467
- </tr>""")
468
- return "".join(rows)
469
-
470
-
471
- def render_dashboard_html(user: dict, invoices: list) -> str:
472
- plan = user.get("plan", "free")
473
- limits = PLAN_LIMITS.get(plan, PLAN_LIMITS["free"])
474
- used = db.count_invoices_this_month(user["id"]) if user["id"] != -1 else len(invoices)
475
- limit_display = "∞" if limits["invoices"] == float("inf") else limits["invoices"]
476
- chat_enabled = plan in ("pro", "enterprise")
477
- return DASHBOARD_HTML_TMPL.format(
478
- css=BASE_CSS,
479
- app_title=APP_TITLE,
480
- plan_label=limits["label"],
481
- used=used,
482
- limit=limit_display,
483
- invoice_rows=render_invoice_rows(invoices),
484
- chat_disabled="" if chat_enabled else "disabled",
485
- chat_placeholder="" if chat_enabled else '<p class="text-gray-500 text-xs">AI Chat is available on Pro and Enterprise plans.</p>',
486
- )
487
 
488
 
489
  # ---------------------------------------------------------------------------
490
- # Gradio Blocks: hidden RPC bridge + route switching
491
- # ---------------------------------------------------------------------------
492
- with gr.Blocks(title=APP_TITLE, css=".gradio-container {background:#0b0d12}") as demo:
493
-
494
- session_token = gr.State(value=None)
495
- current_route = gr.State(value="landing")
496
-
497
- page = gr.HTML(LANDING_HTML)
498
-
499
- with gr.Row(visible=False, elem_id="op-route-bridge"):
500
- route_input = gr.Textbox(elem_id="op-route-input")
501
- with gr.Row(visible=False, elem_id="op-route-trigger"):
502
- route_button = gr.Button("route")
503
-
504
- with gr.Row(visible=False, elem_id="op-auth-bridge"):
505
- auth_input = gr.Textbox(elem_id="op-auth-input")
506
- with gr.Row(visible=False, elem_id="op-auth-trigger"):
507
- auth_button = gr.Button("auth")
508
-
509
- with gr.Row(visible=False, elem_id="op-upload-bridge"):
510
- upload_input = gr.Textbox(elem_id="op-upload-input")
511
- with gr.Row(visible=False, elem_id="op-upload-trigger"):
512
- upload_button = gr.Button("upload")
513
-
514
- with gr.Row(visible=False, elem_id="op-checkout-bridge"):
515
- checkout_input = gr.Textbox(elem_id="op-checkout-input")
516
- with gr.Row(visible=False, elem_id="op-checkout-trigger"):
517
- checkout_button = gr.Button("checkout")
518
-
519
- with gr.Row(visible=False, elem_id="op-chat-bridge"):
520
- chat_input = gr.Textbox(elem_id="op-chat-input-hidden")
521
- with gr.Row(visible=False, elem_id="op-chat-trigger"):
522
- chat_button = gr.Button("chat")
523
-
524
- # -- Route handling ------------------------------------------------
525
- def handle_route(route: str, token: str):
526
- route = (route or "landing").strip()
527
- if route == "logout":
528
- auth.logout(token)
529
- return LANDING_HTML, None, "landing"
530
- if route == "dashboard":
531
- user = auth.get_current_user(token) if token else None
532
- if not user:
533
- return render_login_html(), token, "login"
534
- invoices = db.list_invoices(user["id"]) if user["id"] != -1 else []
535
- return render_dashboard_html(user, invoices), token, "dashboard"
536
- if route == "login":
537
- return render_login_html(), token, "login"
538
- if route == "register":
539
- return render_register_html(), token, "register"
540
- if route == "legal":
541
- return LEGAL_HTML, token, "legal"
542
- if route == "pricing":
543
- return LANDING_HTML, token, "landing"
544
- return LANDING_HTML, token, "landing"
545
-
546
- route_button.click(
547
- handle_route,
548
- inputs=[route_input, session_token],
549
- outputs=[page, session_token, current_route],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550
  )
551
 
552
- # -- Auth handling ---------------------------------------------------
553
- def handle_auth(payload_json: str, token: str, request: gr.Request):
554
- client_ip = request.client.host if request and request.client else "unknown"
555
- try:
556
- payload = json.loads(payload_json) if payload_json else {}
557
- except json.JSONDecodeError:
558
- return render_login_html(), token, "login"
559
 
560
- action = payload.get("action")
561
- try:
562
- if action == "login":
563
- result = auth.login(payload.get("email", ""), payload.get("password", ""), client_ip)
564
- new_token = result["token"]
565
- user = result["user"]
566
- invoices = db.list_invoices(user["id"]) if user["id"] != -1 else []
567
- return render_dashboard_html(user, invoices), new_token, "dashboard"
568
-
569
- if action == "register":
570
- result = auth.register(
571
- payload.get("email", ""), payload.get("name", ""),
572
- payload.get("password", ""), client_ip,
573
- )
574
- new_token = result["token"]
575
- user = result["user"]
576
- return render_dashboard_html(user, []), new_token, "dashboard"
577
-
578
- if action == "reset":
579
- auth.request_password_reset(payload.get("email", ""), client_ip)
580
- return render_login_html(), token, "login"
581
-
582
- except auth.AuthError as exc:
583
- logger.info("Auth error: %s", exc.message)
584
- error_html = render_login_html() if action == "login" else render_register_html()
585
- error_html = error_html.replace(
586
- 'id="op-auth-error" class="hidden',
587
- f'id="op-auth-error" class="op-fade-in',
588
- ).replace(
589
- '></div>', f'>{exc.message}</div>', 1,
590
- )
591
- return error_html, token, action or "login"
592
 
593
- return render_login_html(), token, "login"
594
 
595
- auth_button.click(
596
- handle_auth,
597
- inputs=[auth_input, session_token],
598
- outputs=[page, session_token, current_route],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
599
  )
600
 
601
- # -- Upload / processing pipeline ------------------------------------
602
- def handle_upload(payload_json: str, token: str):
603
- user = auth.get_current_user(token) if token else None
604
- if not user:
605
- return render_login_html(), token
606
 
607
- try:
608
- payload = json.loads(payload_json)
609
- filename = payload["filename"]
610
- raw_bytes = backend._bytes_from_base64(payload["data"])
611
- except Exception as exc:
612
- logger.warning("Bad upload payload: %s", exc)
613
- invoices = db.list_invoices(user["id"]) if user["id"] != -1 else []
614
- return render_dashboard_html(user, invoices), token
 
 
 
 
 
 
615
 
616
- try:
617
- parsed = backend.process_invoice_file(raw_bytes, filename)
618
- if user["id"] != -1:
619
- db.save_invoice_record(user["id"], filename, parsed)
620
- except backend.UploadTooLarge:
621
- logger.info("Upload rejected: file too large.")
622
- except Exception as exc:
623
- logger.error("Processing failed for %s: %s", filename, exc)
624
-
625
- invoices = db.list_invoices(user["id"]) if user["id"] != -1 else []
626
- return render_dashboard_html(user, invoices), token
627
-
628
- upload_button.click(
629
- handle_upload,
630
- inputs=[upload_input, session_token],
631
- outputs=[page, session_token],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
632
  )
633
 
634
- # -- Checkout (Stripe) -------------------------------------------------
635
- def handle_checkout(plan: str, token: str):
636
- user = auth.get_current_user(token) if token else None
637
  if not user:
638
- return render_register_html(), token, "register"
639
- if plan == "enterprise":
640
- return render_dashboard_html(user, db.list_invoices(user["id"]) if user["id"] != -1 else []), token, "dashboard"
641
- # In production: create a Stripe Checkout Session here with
642
- # client_reference_id=user["id"] and redirect the browser to
643
- # session.url. Left as an integration point tied to your Stripe
644
- # account's live Price IDs.
645
- invoices = db.list_invoices(user["id"]) if user["id"] != -1 else []
646
- return render_dashboard_html(user, invoices), token, "dashboard"
647
-
648
- checkout_button.click(
649
- handle_checkout,
650
- inputs=[checkout_input, session_token],
651
- outputs=[page, session_token, current_route],
652
  )
653
 
654
- # -- AI Chat (Pro+) ----------------------------------------------------
655
- def handle_chat(message: str, token: str):
656
- user = auth.get_current_user(token) if token else None
657
- if not user or user.get("plan") not in ("pro", "enterprise"):
658
- invoices = db.list_invoices(user["id"]) if user and user["id"] != -1 else []
659
- return render_dashboard_html(user, invoices) if user else render_login_html(), token
660
-
661
- invoices = db.list_invoices(user["id"]) if user["id"] != -1 else []
662
- context = json.dumps(invoices[:50], default=str)
663
- reply = "AI Chat requires GROQ_API_KEY to be configured."
664
- if backend.GROQ_API_KEY:
665
- try:
666
- import requests as _requests
667
- resp = _requests.post(
668
- "https://api.groq.com/openai/v1/chat/completions",
669
- headers={"Authorization": f"Bearer {backend.GROQ_API_KEY}"},
670
- json={
671
- "model": "llama-3.1-8b-instant",
672
- "messages": [
673
- {"role": "system", "content": f"You answer questions about this invoice data: {context[:6000]}"},
674
- {"role": "user", "content": message},
675
- ],
676
- "temperature": 0.2,
677
- },
678
- timeout=15,
679
- )
680
- resp.raise_for_status()
681
- reply = resp.json()["choices"][0]["message"]["content"]
682
- except Exception as exc:
683
- logger.warning("Chat request failed: %s", exc)
684
- reply = "Sorry, the AI Chat service is temporarily unavailable."
685
-
686
- dashboard = render_dashboard_html(user, invoices)
687
- safe_reply = reply.replace("`", "'").replace("</", "<\\/")
688
- dashboard += f"""<script>
689
- document.getElementById('op-chat-log').innerHTML +=
690
- `<div><span class="inline-block bg-gray-800 rounded-lg px-3 py-2">{safe_reply}</span></div>`;
691
- </script>"""
692
- return dashboard, token
693
-
694
- chat_button.click(
695
- handle_chat,
696
- inputs=[chat_input, session_token],
697
- outputs=[page, session_token],
698
  )
699
 
 
 
 
 
 
700
 
701
- # ---------------------------------------------------------------------------
702
- # Mount Gradio on a FastAPI app so we can add a raw-body Stripe webhook route.
703
- # The webhook needs the unparsed request body + the `stripe-signature` header
704
- # for signature verification, which Gradio components cannot provide.
705
- # ---------------------------------------------------------------------------
706
- from fastapi import FastAPI, Request as FastAPIRequest
 
 
 
 
707
 
708
- fastapi_app = FastAPI()
 
 
 
 
709
 
 
 
 
 
 
 
 
 
 
 
710
 
711
- @fastapi_app.post("/stripe/webhook")
712
- async def stripe_webhook(request: FastAPIRequest):
713
- return await backend.stripe_webhook_handler(request)
 
 
 
714
 
 
 
 
 
 
 
 
 
 
 
715
 
716
- app = gr.mount_gradio_app(fastapi_app, demo, path="/")
 
 
 
 
717
 
 
 
 
 
 
 
 
 
 
 
 
 
 
718
 
719
- if __name__ == "__main__":
720
- import uvicorn
721
 
 
 
 
 
722
  demo.queue()
723
- uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", 7860)))
 
1
  """
2
+ OmniParse AI — Invoice processing SaaS
3
+ Refactored, modular Gradio app for HuggingFace Spaces.
4
+
5
+ Views: Landing / Pricing / Legal / Auth / Dashboard
6
+ All AI/OCR/DB layers degrade gracefully if a given secret/service is missing.
7
+
8
+ Security: bcrypt passwords, rate limiting, server-side validation,
9
+ file size limits, input sanitization, no raw HTML from users.
10
+ UI: Custom SVG icons, skeleton loaders, tooltips, dark mode,
11
+ toast notifications, drag-and-drop upload, semantic HTML.
 
12
  """
13
 
14
  import os
15
+ import csv
16
  import json
17
+ from datetime import datetime, timezone
 
18
 
19
  import gradio as gr
20
 
21
+ # ---------------------------------------------------------------------------
22
+ # Module imports — all with graceful fallback
23
+ # ---------------------------------------------------------------------------
24
+ try:
25
+ from config import (
26
+ APP_URL, GROQ_CLIENT, PLAN_LIMITS, PLAN_LABELS, PLAN_PRICES,
27
+ MAX_FILE_SIZE_BYTES, ALLOWED_EXTENSIONS, SESSION_TTL_HOURS,
28
+ )
29
+ except ImportError:
30
+ APP_URL = os.environ.get("APP_URL", "http://localhost:7860")
31
+ GROQ_CLIENT = None
32
+ PLAN_LIMITS = {"free": 20, "basic": 200, "pro": 2000, "enterprise": float("inf")}
33
+ PLAN_LABELS = {"free": "Free", "basic": "Basic", "pro": "Pro", "enterprise": "Enterprise"}
34
+ PLAN_PRICES = {"free": 0, "basic": 29, "pro": 129, "enterprise": 499}
35
+ MAX_FILE_SIZE_BYTES = 20 * 1024 * 1024
36
+ ALLOWED_EXTENSIONS = {"pdf", "jpg", "jpeg", "png", "tiff", "tif"}
37
+ SESSION_TTL_HOURS = 168
38
+
39
+ try:
40
+ from database import (
41
+ db_init, get_user_by_email, get_user_by_id, update_user,
42
+ get_session_user, delete_session,
43
+ insert_invoice, get_invoices, count_invoices_this_month,
44
+ delete_invoice,
45
+ )
46
+ except ImportError:
47
+ db_init = lambda: None
48
+ get_user_by_email = lambda e: None
49
+ get_user_by_id = lambda i: None
50
+ update_user = lambda *a: None
51
+ get_session_user = lambda t: None
52
+ delete_session = lambda t: None
53
+ insert_invoice = lambda *a: {}
54
+ get_invoices = lambda u: []
55
+ count_invoices_this_month = lambda u: 0
56
+ delete_invoice = lambda *a: None
57
+
58
+ try:
59
+ from auth import (
60
+ create_user, authenticate_user, gen_api_key,
61
+ create_session, hash_pw,
62
+ )
63
+ except ImportError:
64
+ create_user = lambda *a: (None, "Auth module not available")
65
+ authenticate_user = lambda *a: (None, "Auth module not available")
66
+ gen_api_key = lambda: "op_live_fallback"
67
+ create_session = lambda u: "fallback_token"
68
+ hash_pw = lambda p: p
69
+
70
+ try:
71
+ from validation import validate_email, validate_password, validate_name, validate_file
72
+ except ImportError:
73
+ validate_email = lambda e: (bool(e), "")
74
+ validate_password = lambda p: (len(p) >= 8, "Password too short" if len(p) < 8 else "")
75
+ validate_name = lambda n: (bool(n), "")
76
+ validate_file = lambda f: (True, "")
77
+
78
+ try:
79
+ from rate_limiter import check_auth_rate, check_upload_rate, check_chat_rate
80
+ except ImportError:
81
+ check_auth_rate = lambda ip: True
82
+ check_upload_rate = lambda ip: True
83
+ check_chat_rate = lambda ip: True
84
+
85
+ try:
86
+ import icons as ic
87
+ except ImportError:
88
+ ic = None
89
+
90
+ try:
91
+ import html_templates as tmpl
92
+ except ImportError:
93
+ tmpl = None
94
+
95
+ try:
96
+ from ocr_pipeline import process_file as ocr_process_file
97
+ except ImportError:
98
+ ocr_process_file = None
99
+
100
+ try:
101
+ from stripe_handler import create_checkout_session, verify_checkout_session
102
+ except ImportError:
103
+ create_checkout_session = lambda *a: (None, "Payments not configured")
104
+ verify_checkout_session = lambda *a: ("Verification unavailable", None)
105
+
106
+ try:
107
+ from invoice_processor import (
108
+ validate_invoice_data, _parse_date_any, process_and_save, batch_process,
109
+ )
110
+ except ImportError:
111
+ validate_invoice_data = lambda d: []
112
+ _parse_date_any = lambda s: None
113
+ process_and_save = lambda *a: ({}, {})
114
+ batch_process = lambda *a: ([], [], 0, 0)
115
 
116
+ # ---------------------------------------------------------------------------
117
+ # Initialize
118
+ # ---------------------------------------------------------------------------
119
+ db_init()
120
+ try:
121
+ from auth import ensure_demo_account
122
+ ensure_demo_account()
123
+ except ImportError:
124
+ pass
125
 
126
+ # ---------------------------------------------------------------------------
127
+ # Helper: get client IP from Gradio request
128
+ # ---------------------------------------------------------------------------
129
+ def _get_ip(request: gr.Request) -> str:
130
+ try:
131
+ return request.client.host if request and request.client else "unknown"
132
+ except Exception:
133
+ return "unknown"
134
 
 
 
 
 
 
 
135
 
136
  # ---------------------------------------------------------------------------
137
+ # View management
138
+ # ---------------------------------------------------------------------------
139
+ ALL_VIEWS = [] # populated after Blocks creation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
+ def show_only(idx):
143
+ return [gr.update(visible=(i == idx)) for i in range(len(ALL_VIEWS))]
144
+
 
145
 
146
  # ---------------------------------------------------------------------------
147
+ # Navigation callbacks
148
+ # ---------------------------------------------------------------------------
149
+ def go_landing():
150
+ return show_only(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
 
153
+ def go_pricing():
154
+ return show_only(1)
155
+
156
+
157
+ def go_legal():
158
+ return show_only(2)
159
+
160
+
161
+ def go_auth():
162
+ return show_only(3)
163
+
164
+
165
+ def go_dashboard():
166
+ return show_only(4)
167
+
168
+
169
+ # ---------------------------------------------------------------------------
170
+ # Auth callbacks
171
+ # ---------------------------------------------------------------------------
172
+ def do_login(email, password, request: gr.Request):
173
+ ip = _get_ip(request)
174
+ if not check_auth_rate(ip):
175
+ return (
176
+ gr.update(value="Too many login attempts. Please wait a moment.", visible=True),
177
+ None, None,
178
+ *show_only(3), gr.update(), gr.update(), gr.update(), gr.update(),
179
+ )
180
+ if not email or not password:
181
+ return (
182
+ gr.update(value="Please enter both email and password.", visible=True),
183
+ None, None,
184
+ *show_only(3), gr.update(), gr.update(), gr.update(), gr.update(),
185
+ )
186
+ user, err = authenticate_user(email, password, ip)
187
+ if err:
188
+ return (
189
+ gr.update(value=err, visible=True),
190
+ None, None,
191
+ *show_only(3), gr.update(), gr.update(), gr.update(), gr.update(),
192
+ )
193
+ token = create_session(str(user["id"]))
194
+ return (
195
+ gr.update(value="", visible=False),
196
+ token, user,
197
+ *show_only(4),
198
+ gr.update(visible=False), gr.update(visible=False),
199
+ gr.update(visible=True), gr.update(visible=True),
200
+ )
201
 
202
 
203
+ def do_signup(name, email, password, terms, request: gr.Request):
204
+ ip = _get_ip(request)
205
+ if not check_auth_rate(ip):
206
+ return (
207
+ gr.update(value="Too many registration attempts. Please wait a moment.", visible=True),
208
+ None, None,
209
+ *show_only(3), gr.update(), gr.update(), gr.update(), gr.update(),
210
+ )
211
+ # Server-side validation
212
+ valid, msg = validate_name(name)
213
+ if not valid:
214
+ return (
215
+ gr.update(value=f"Invalid name: {msg}", visible=True),
216
+ None, None,
217
+ *show_only(3), gr.update(), gr.update(), gr.update(), gr.update(),
218
+ )
219
+ valid, msg = validate_email(email)
220
+ if not valid:
221
+ return (
222
+ gr.update(value=f"Invalid email: {msg}", visible=True),
223
+ None, None,
224
+ *show_only(3), gr.update(), gr.update(), gr.update(), gr.update(),
225
+ )
226
+ valid, pw_msgs = validate_password(password)
227
+ if not valid:
228
+ details = "; ".join(pw_msgs)
229
+ return (
230
+ gr.update(value=f"Password requirements not met: {details}", visible=True),
231
+ None, None,
232
+ *show_only(3), gr.update(), gr.update(), gr.update(), gr.update(),
233
+ )
234
+ if not terms:
235
+ return (
236
+ gr.update(value="You must agree to the Terms of Use and Privacy Policy.", visible=True),
237
+ None, None,
238
+ *show_only(3), gr.update(), gr.update(), gr.update(), gr.update(),
239
+ )
240
+ user, err = create_user(email, name, password)
241
+ if err:
242
+ return (
243
+ gr.update(value=err, visible=True),
244
+ None, None,
245
+ *show_only(3), gr.update(), gr.update(), gr.update(), gr.update(),
246
+ )
247
+ token = create_session(str(user["id"]))
248
+ return (
249
+ gr.update(value="", visible=False),
250
+ token, user,
251
+ *show_only(4),
252
+ gr.update(visible=False), gr.update(visible=False),
253
+ gr.update(visible=True), gr.update(visible=True),
254
  )
255
 
256
 
257
+ def do_logout(token):
258
+ if token:
259
+ delete_session(token)
260
+ return (
261
+ None, None,
262
+ *show_only(0),
263
+ gr.update(visible=True), gr.update(visible=True),
264
+ gr.update(visible=False), gr.update(visible=False),
 
 
265
  )
266
 
267
 
268
+ # ---------------------------------------------------------------------------
269
+ # Dashboard load / usage
270
+ # ---------------------------------------------------------------------------
271
+ def load_dashboard(user):
272
+ if not user:
273
+ return "## Dashboard\n\n_You are not signed in._", ""
274
+ used = count_invoices_this_month(user["id"])
275
+ limit = PLAN_LIMITS.get(user["plan"], 20)
276
+ limit_str = "\u221e" if limit == float("inf") else str(int(limit))
277
+ plan_label = PLAN_LABELS.get(user["plan"], user["plan"])
278
+ welcome = f"## Dashboard\n\nWelcome back, **{user['name']}** (Plan: {plan_label})"
279
+ usage = f"**{used}/{limit_str} invoices used this month**"
280
+ if limit != float("inf") and used >= limit:
281
+ usage += "\n\n**Monthly limit reached.** Go to the Upgrade tab to increase your limit."
282
+ return welcome, usage
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
 
284
 
285
+ # ---------------------------------------------------------------------------
286
+ # Upload / processing
287
+ # ---------------------------------------------------------------------------
288
+ def do_upload(files, user, request: gr.Request):
289
+ ip = _get_ip(request)
290
+ if not user:
291
+ return "You must be signed in to upload invoices.", [], None, ""
292
+ if not files:
293
+ return "No files selected. Please select invoice files to process.", [], None, ""
294
+ if not check_upload_rate(ip):
295
+ return "Upload rate limit reached. Please wait a moment.", [], None, ""
296
+
297
+ limit = PLAN_LIMITS.get(user["plan"], 20)
298
+ used = count_invoices_this_month(user["id"])
299
+ rows = []
300
+ last_json = None
301
+ processed = 0
302
+
303
+ for f in files:
304
+ if used + processed >= limit:
305
+ break
306
+ path = f.name if hasattr(f, "name") else f
307
+ filename = os.path.basename(path)
308
+
309
+ # Server-side file validation
310
+ valid, err = validate_file(path)
311
+ if not valid:
312
+ rows.append([filename, "Validation Error", None, None, None, err])
313
+ continue
314
+
315
+ try:
316
+ if ocr_process_file:
317
+ data = ocr_process_file(path, user)
318
+ else:
319
+ data = {
320
+ "filename": filename, "vendor": "Demo Vendor Inc.",
321
+ "invoice_number": "DEMO-0001",
322
+ "invoice_date": datetime.now().strftime("%Y-%m-%d"),
323
+ "due_date": None, "amount": 100.0, "vat_amount": 21.0,
324
+ "total": 121.0, "currency": "USD", "line_items": [],
325
+ }
326
+ except Exception as e:
327
+ data = {
328
+ "filename": filename, "vendor": None, "invoice_number": None,
329
+ "invoice_date": None, "due_date": None, "amount": None,
330
+ "vat_amount": None, "total": None, "currency": "USD",
331
+ "status": "review", "confidence": 0,
332
+ "warnings": [f"Processing error: {str(e)[:200]}"],
333
+ }
334
+
335
+ # Validate extracted data
336
+ warnings = validate_invoice_data(data)
337
+ if warnings:
338
+ data["warnings"] = data.get("warnings", []) + warnings
339
+ if data.get("status") != "duplicate":
340
+ data["status"] = "review"
341
+
342
+ saved = insert_invoice(user["id"], data)
343
+ last_json = data
344
+ status_label = data.get("status", "done")
345
+ status_display = {
346
+ "done": "Done", "review": "Review",
347
+ "duplicate": "Duplicate", "processing": "Processing",
348
+ }.get(status_label, status_label)
349
+ rows.append([
350
+ data.get("filename"), data.get("vendor"),
351
+ data.get("invoice_number"), data.get("invoice_date"),
352
+ data.get("total"), status_display,
353
+ ])
354
+ processed += 1
355
+
356
+ skipped = len(files) - processed
357
+ msg = f"Successfully processed {processed} invoice{'s' if processed != 1 else ''}."
358
+ if skipped > 0:
359
+ msg += f" {skipped} file{'s' if skipped != 1 else ''} skipped \u2014 monthly limit reached. Upgrade your plan to process more."
360
+
361
+ used_new = count_invoices_this_month(user["id"])
362
+ limit_str = "\u221e" if limit == float("inf") else str(int(limit))
363
+ usage = f"**{used_new}/{limit_str} invoices used this month**"
364
+ return msg, rows, last_json, usage
365
+
366
+
367
+ # ---------------------------------------------------------------------------
368
+ # My Invoices
369
+ # ---------------------------------------------------------------------------
370
+ STATUS_MAP = {
371
+ "done": "Done", "review": "Review",
372
+ "duplicate": "Duplicate", "processing": "Processing",
373
+ }
374
+
375
+
376
+ def refresh_invoices(user, flt):
377
+ if not user:
378
+ return []
379
+ invoices = get_invoices(user["id"])
380
  rows = []
381
  for inv in invoices:
382
  status = inv.get("status", "done")
383
+ if flt == "Done" and status != "done":
384
+ continue
385
+ if flt == "Review" and status != "review":
386
+ continue
387
+ if flt == "Duplicates" and not inv.get("is_duplicate"):
388
+ continue
389
+ rows.append([
390
+ inv.get("id"), inv.get("vendor"), inv.get("inv_number"),
391
+ inv.get("inv_date"), inv.get("total"),
392
+ STATUS_MAP.get(status, status),
393
+ ])
394
+ return rows
395
+
396
+
397
+ def do_delete_invoice(user, inv_id):
398
+ if not user or not inv_id:
399
+ return "Please enter a valid invoice ID.", []
400
+ inv_id = int(inv_id)
401
+ delete_invoice(user["id"], inv_id)
402
+ return f"Invoice #{inv_id} has been deleted.", refresh_invoices(user, "All")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
403
 
404
 
405
  # ---------------------------------------------------------------------------
406
+ # AI Chat
407
+ # ---------------------------------------------------------------------------
408
+ def chat_respond(message, history, user, request: gr.Request):
409
+ history = history or []
410
+ if not user:
411
+ history.append({"role": "assistant", "content": "You must be signed in to use AI Chat."})
412
+ return history, ""
413
+ if not check_chat_rate(_get_ip(request)):
414
+ history.append({"role": "assistant", "content": "Chat rate limit reached. Please wait a moment."})
415
+ return history, ""
416
+ if user["plan"] not in ("pro", "enterprise"):
417
+ history.append({
418
+ "role": "assistant",
419
+ "content": "AI Chat is available on the Pro plan and above. Upgrade from the Upgrade tab to unlock this feature.",
420
+ })
421
+ return history, ""
422
+ if not message or not message.strip():
423
+ return history, ""
424
+
425
+ invoices = get_invoices(user["id"])
426
+ context = json.dumps(invoices[:100], default=str, ensure_ascii=False)[:6000]
427
+ history.append({"role": "user", "content": message})
428
+
429
+ if GROQ_CLIENT:
430
+ try:
431
+ resp = GROQ_CLIENT.chat.completions.create(
432
+ model="llama-3.1-8b-instant",
433
+ messages=[
434
+ {
435
+ "role": "system",
436
+ "content": (
437
+ "You are an assistant answering questions about the user's invoices. "
438
+ f"Here is their invoice data as JSON: {context}. "
439
+ "Answer concisely based only on this data. Use plain text, no markdown."
440
+ ),
441
+ },
442
+ {"role": "user", "content": message},
443
+ ],
444
+ max_tokens=400, temperature=0.2, timeout=10,
445
+ )
446
+ answer = resp.choices[0].message.content
447
+ except Exception as e:
448
+ answer = f"AI is temporarily unavailable ({str(e)[:100]}). Please try again."
449
+ else:
450
+ answer = "AI Chat requires the GROQ_API_KEY to be configured."
451
+
452
+ history.append({"role": "assistant", "content": answer})
453
+ return history, ""
454
+
455
+
456
+ # ---------------------------------------------------------------------------
457
+ # Export
458
+ # ---------------------------------------------------------------------------
459
+ def export_csv(user):
460
+ if not user:
461
+ return None
462
+ invoices = get_invoices(user["id"])
463
+ path = f"/tmp/omniparse_export_{user['id']}.csv"
464
+ with open(path, "w", newline="", encoding="utf-8") as f:
465
+ writer = csv.writer(f)
466
+ writer.writerow([
467
+ "ID", "Vendor", "Invoice #", "Date", "Due Date",
468
+ "Amount", "VAT", "Total", "Currency", "Status",
469
+ ])
470
+ for inv in invoices:
471
+ writer.writerow([
472
+ inv.get("id"), inv.get("vendor"), inv.get("inv_number"),
473
+ inv.get("inv_date"), inv.get("due_date"), inv.get("amount"),
474
+ inv.get("vat_amount"), inv.get("total"), inv.get("currency"),
475
+ inv.get("status"),
476
+ ])
477
+ return path
478
+
479
+
480
+ def export_json(user):
481
+ if not user:
482
+ return None
483
+ if user["plan"] == "free":
484
+ return None
485
+ invoices = get_invoices(user["id"])
486
+ path = f"/tmp/omniparse_export_{user['id']}.json"
487
+ with open(path, "w", encoding="utf-8") as f:
488
+ json.dump(invoices, f, default=str, ensure_ascii=False, indent=2)
489
+ return path
490
+
491
+
492
+ # ---------------------------------------------------------------------------
493
+ # Upgrade / Stripe
494
+ # ---------------------------------------------------------------------------
495
+ def do_upgrade(plan, user):
496
+ if not user:
497
+ return "You must be signed in to upgrade."
498
+ url, err = create_checkout_session(plan, user)
499
+ if err:
500
+ return err
501
+ return (
502
+ f"[Complete your payment via Stripe]({url})\n\n"
503
+ "After paying, return here and paste the `session_id` from the URL below."
504
  )
505
 
 
 
 
 
 
 
 
506
 
507
+ def do_check_payment(session_id, user):
508
+ if not user or not session_id:
509
+ return "Please enter a valid session ID."
510
+ msg, err = verify_checkout_session(session_id, user["id"])
511
+ if err:
512
+ return err
513
+ return msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
514
 
 
515
 
516
+ # ---------------------------------------------------------------------------
517
+ # API tab
518
+ # ---------------------------------------------------------------------------
519
+ def load_api_tab(user):
520
+ if not user:
521
+ return (
522
+ gr.update(visible=True, value="You must be signed in."),
523
+ gr.update(visible=False), gr.update(visible=False),
524
+ )
525
+ if user["plan"] not in ("pro", "enterprise"):
526
+ return (
527
+ gr.update(
528
+ visible=True,
529
+ value="API access is available on the Pro plan and above. "
530
+ "Upgrade from the Upgrade tab to get your API key.",
531
+ ),
532
+ gr.update(visible=False), gr.update(visible=False),
533
+ )
534
+ key = user.get("api_key") or "\u2014"
535
+ snippet = (
536
+ f"```bash\n"
537
+ f"curl -X POST {APP_URL}/api/extract \\\n"
538
+ f' -H "Authorization: Bearer {key}" \\\n'
539
+ f" -F \"file=@invoice.pdf\"\n"
540
+ f"```"
541
+ )
542
+ return (
543
+ gr.update(visible=False),
544
+ gr.update(visible=True, value=f"**Your API Key:** `{key}`"),
545
+ gr.update(visible=True, value=snippet),
546
  )
547
 
 
 
 
 
 
548
 
549
+ # ---------------------------------------------------------------------------
550
+ # Profile
551
+ # ---------------------------------------------------------------------------
552
+ def load_profile(user):
553
+ if not user:
554
+ return "You are not signed in."
555
+ plan = PLAN_LABELS.get(user["plan"], user["plan"])
556
+ price = PLAN_PRICES.get(user["plan"], 0)
557
+ return (
558
+ f"**Name:** {user['name']}\n\n"
559
+ f"**Email:** {user['email']}\n\n"
560
+ f"**Plan:** {plan} (${price}/mo)\n\n"
561
+ f"**Created:** {(user.get('created_at') or '')[:10]}"
562
+ )
563
 
564
+
565
+ def do_change_password(user, new_pw, request: gr.Request):
566
+ if not user:
567
+ return "You must be signed in."
568
+ valid, pw_msgs = validate_password(new_pw)
569
+ if not valid:
570
+ details = "; ".join(pw_msgs)
571
+ return f"Password requirements not met: {details}"
572
+ update_user(str(user["id"]), {"password": hash_pw(new_pw)})
573
+ return "Password has been changed successfully."
574
+
575
+
576
+ def do_delete_account(user, token):
577
+ if not user:
578
+ return "You must be signed in.", None, None
579
+ uid = str(user["id"])
580
+ try:
581
+ from database import _sqlite_conn
582
+ conn = _sqlite_conn()
583
+ conn.execute("DELETE FROM invoices WHERE user_id=?", (uid,))
584
+ conn.execute("DELETE FROM users WHERE id=?", (uid,))
585
+ conn.commit()
586
+ conn.close()
587
+ except Exception:
588
+ pass
589
+ if token:
590
+ delete_session(token)
591
+ return "Your account has been permanently deleted.", None, None
592
+
593
+
594
+ # ---------------------------------------------------------------------------
595
+ # Build Gradio App
596
+ # ---------------------------------------------------------------------------
597
+ CUSTOM_CSS = tmpl.BASE_CSS if tmpl else ""
598
+
599
+ with gr.Blocks(
600
+ title="OmniParse AI",
601
+ css=CUSTOM_CSS,
602
+ theme=gr.themes.Soft(primary_hue="violet"),
603
+ head=(
604
+ (tmpl.ALL_JS if tmpl else "") +
605
+ (tmpl.DARK_MODE_JS if tmpl else "")
606
+ ),
607
+ ) as demo:
608
+
609
+ session_token = gr.State(None)
610
+ current_user = gr.State(None)
611
+
612
+ # ===================== NAVBAR =====================
613
+ with gr.Row(elem_id="op-navbar"):
614
+ if tmpl:
615
+ gr.HTML(tmpl.navbar_html())
616
+ else:
617
+ gr.HTML('<div class="op-logo"><span>OmniParse AI</span></div>')
618
+ with gr.Row():
619
+ nav_pricing_btn = gr.Button("Pricing", size="sm", variant="secondary")
620
+ nav_legal_btn = gr.Button("Legal", size="sm", variant="secondary")
621
+ nav_login_btn = gr.Button("Log In", size="sm", variant="secondary")
622
+ nav_start_btn = gr.Button("Start Free", size="sm", variant="primary")
623
+ nav_dashboard_btn = gr.Button("Dashboard", size="sm", variant="primary", visible=False)
624
+ nav_logout_btn = gr.Button("Log Out", size="sm", variant="secondary", visible=False)
625
+
626
+ # ===================== VIEW 0: LANDING =====================
627
+ with gr.Column(visible=True) as view_landing:
628
+ if tmpl:
629
+ gr.HTML(tmpl.landing_html())
630
+ else:
631
+ gr.Markdown("# OmniParse AI\n\nInvoice processing in seconds, not hours.")
632
+ with gr.Row():
633
+ landing_cta_btn = gr.Button("Start Free \u2014 20 invoices", variant="primary", scale=1)
634
+ if tmpl:
635
+ gr.HTML(tmpl.footer_html())
636
+
637
+ # ===================== VIEW 1: PRICING =====================
638
+ with gr.Column(visible=False) as view_pricing:
639
+ gr.Markdown("## Pricing")
640
+ gr.HTML(tmpl.pricing_html() if tmpl else "<p>Pricing information unavailable.</p>")
641
+ gr.Markdown(
642
+ "Enterprise annual plan: **$4,188/year** "
643
+ "(save 2 months compared to monthly billing)."
644
+ )
645
+ with gr.Accordion("Frequently asked questions about payments", open=False):
646
+ gr.Markdown(
647
+ "- **What payment methods do you accept?** "
648
+ "Card payments via Stripe (Visa, Mastercard, Amex).\n"
649
+ "- **Can I change plans at any time?** "
650
+ "Yes, upgrade or downgrade from Dashboard \u2192 Upgrade.\n"
651
+ "- **Do you offer refunds?** "
652
+ "Within 14 days of your first payment, upon request."
653
+ )
654
+ pricing_back_btn = gr.Button("Back to Home")
655
+
656
+ # ===================== VIEW 2: LEGAL =====================
657
+ with gr.Column(visible=False) as view_legal:
658
+ gr.HTML(tmpl.legal_html() if tmpl else "<h2>Legal</h2>")
659
+ legal_back_btn = gr.Button("Back to Home")
660
+
661
+ # ===================== VIEW 3: AUTH =====================
662
+ with gr.Column(visible=False) as view_auth:
663
+ gr.Markdown("## Welcome to OmniParse AI")
664
+ if tmpl:
665
+ gr.HTML(tmpl.auth_hint_html())
666
+ with gr.Tabs():
667
+ with gr.Tab("Log In"):
668
+ login_email = gr.Textbox(label="Email", placeholder="you@company.com")
669
+ login_password = gr.Textbox(label="Password", type="password", placeholder="Enter your password")
670
+ login_btn = gr.Button("Log In", variant="primary")
671
+ login_error = gr.Markdown(visible=False)
672
+
673
+ with gr.Tab("Sign Up"):
674
+ signup_name = gr.Textbox(label="Full Name", placeholder="Jane Smith")
675
+ signup_email = gr.Textbox(label="Work Email", placeholder="you@company.com")
676
+ signup_password = gr.Textbox(
677
+ label="Password",
678
+ type="password",
679
+ placeholder="Minimum 8 characters, mixed case, digit, and special character",
680
+ )
681
+ signup_terms = gr.Checkbox(
682
+ label="I agree to the Terms of Use and Privacy Policy"
683
+ )
684
+ signup_btn = gr.Button("Create Account", variant="primary")
685
+ signup_error = gr.Markdown(visible=False)
686
+
687
+ # ===================== VIEW 4: DASHBOARD =====================
688
+ with gr.Column(visible=False) as view_dashboard:
689
+ dash_welcome = gr.Markdown("## Dashboard")
690
+ with gr.Tabs():
691
+
692
+ # --- Upload ---
693
+ with gr.Tab("Upload"):
694
+ usage_md = gr.Markdown()
695
+ if tmpl:
696
+ gr.HTML(tmpl.upload_dropzone_html())
697
+ upload_files = gr.File(
698
+ label="Upload invoices (PDF, JPG, PNG, TIFF \u2014 max 20 MB each)",
699
+ file_count="multiple",
700
+ )
701
+ upload_btn = gr.Button("Process Invoices", variant="primary")
702
+ upload_status = gr.Markdown()
703
+ upload_table = gr.Dataframe(
704
+ headers=[
705
+ "Filename", "Vendor", "Invoice #",
706
+ "Date", "Total", "Status",
707
+ ],
708
+ label="Results",
709
+ interactive=False,
710
+ )
711
+ upload_json = gr.JSON(label="Raw output (last invoice)")
712
+
713
+ # --- My Invoices ---
714
+ with gr.Tab("My Invoices"):
715
+ invoices_filter = gr.Radio(
716
+ ["All", "Done", "Review", "Duplicates"],
717
+ value="All",
718
+ label="Filter",
719
+ )
720
+ refresh_invoices_btn = gr.Button("Refresh")
721
+ invoices_table = gr.Dataframe(
722
+ headers=["ID", "Vendor", "Invoice #", "Date", "Total", "Status"],
723
+ label="Invoices",
724
+ interactive=False,
725
+ )
726
+ with gr.Row():
727
+ delete_id_input = gr.Number(
728
+ label="Invoice ID to delete", precision=0
729
+ )
730
+ delete_invoice_btn = gr.Button("Delete", variant="stop")
731
+ delete_status = gr.Markdown()
732
+
733
+ # --- AI Chat ---
734
+ with gr.Tab("AI Chat (Pro+)"):
735
+ chat_lock_msg = gr.Markdown(visible=False)
736
+ chatbot = gr.Chatbot(
737
+ label="Ask about your invoices",
738
+ type="messages",
739
+ )
740
+ chat_input = gr.Textbox(
741
+ label="Message",
742
+ placeholder="What is the total unpaid amount?",
743
+ )
744
+ chat_send_btn = gr.Button("Send", variant="primary")
745
+ gr.Markdown(
746
+ '_Try: "List all invoices from Microsoft" / '
747
+ '"Which invoice has the highest tax?"_'
748
+ )
749
+
750
+ # --- Export ---
751
+ with gr.Tab("Export"):
752
+ gr.Markdown("**CSV Export** \u2014 available on all plans.")
753
+ export_csv_btn = gr.Button("Export CSV")
754
+ export_csv_file = gr.File(label="Download CSV")
755
+ gr.Markdown("**JSON Export** \u2014 Basic plan and above.")
756
+ export_json_btn = gr.Button("Export JSON")
757
+ export_json_file = gr.File(label="Download JSON")
758
+ gr.Markdown("**Excel Export** \u2014 Basic and above (coming soon)")
759
+ gr.Markdown("**Google Sheets Sync** \u2014 Basic and above (coming soon)")
760
+
761
+ # --- Upgrade ---
762
+ with gr.Tab("Upgrade"):
763
+ gr.HTML(tmpl.pricing_html() if tmpl else "")
764
+ upgrade_plan_dd = gr.Dropdown(
765
+ ["basic", "pro", "enterprise"],
766
+ label="Select a plan",
767
+ )
768
+ upgrade_btn = gr.Button("Upgrade via Stripe", variant="primary")
769
+ upgrade_link = gr.Markdown()
770
+ gr.Markdown("---")
771
+ session_id_input = gr.Textbox(
772
+ label="Stripe session_id (paste from URL after payment)"
773
+ )
774
+ check_payment_btn = gr.Button("Verify Payment")
775
+ payment_status_md = gr.Markdown()
776
+
777
+ # --- API ---
778
+ with gr.Tab("API (Pro+)"):
779
+ api_lock_msg = gr.Markdown(visible=False)
780
+ api_key_display = gr.Markdown(visible=False)
781
+ api_docs = gr.Markdown(visible=False)
782
+
783
+ # --- Profile ---
784
+ with gr.Tab("Profile"):
785
+ profile_info = gr.Markdown()
786
+ new_password = gr.Textbox(
787
+ label="New Password",
788
+ type="password",
789
+ placeholder="Enter new password",
790
+ )
791
+ change_pw_btn = gr.Button("Change Password")
792
+ change_pw_status = gr.Markdown()
793
+ gr.Markdown("### Danger Zone")
794
+ delete_account_btn = gr.Button("Delete Account", variant="stop")
795
+ delete_account_status = gr.Markdown()
796
+
797
+ # =================================================================
798
+ # Register all views
799
+ # =================================================================
800
+ ALL_VIEWS.extend([view_landing, view_pricing, view_legal, view_auth, view_dashboard])
801
+
802
+ # =================================================================
803
+ # Navigation wiring
804
+ # =================================================================
805
+ nav_pricing_btn.click(go_pricing, outputs=ALL_VIEWS)
806
+ pricing_back_btn.click(go_landing, outputs=ALL_VIEWS)
807
+ nav_legal_btn.click(go_legal, outputs=ALL_VIEWS)
808
+ legal_back_btn.click(go_landing, outputs=ALL_VIEWS)
809
+ nav_login_btn.click(go_auth, outputs=ALL_VIEWS)
810
+ nav_start_btn.click(go_auth, outputs=ALL_VIEWS)
811
+ landing_cta_btn.click(go_auth, outputs=ALL_VIEWS)
812
+
813
+ # =================================================================
814
+ # Auth wiring
815
+ # =================================================================
816
+ auth_outputs = [
817
+ login_error, session_token, current_user,
818
+ *ALL_VIEWS,
819
+ nav_login_btn, nav_start_btn, nav_dashboard_btn, nav_logout_btn,
820
+ ]
821
+
822
+ login_btn.click(
823
+ do_login,
824
+ inputs=[login_email, login_password],
825
+ outputs=auth_outputs,
826
+ )
827
+ signup_btn.click(
828
+ do_signup,
829
+ inputs=[signup_name, signup_email, signup_password, signup_terms],
830
+ outputs=auth_outputs,
831
+ )
832
+ nav_logout_btn.click(
833
+ do_logout,
834
+ inputs=[session_token],
835
+ outputs=[
836
+ session_token, current_user,
837
+ *ALL_VIEWS,
838
+ nav_login_btn, nav_start_btn, nav_dashboard_btn, nav_logout_btn,
839
+ ],
840
  )
841
 
842
+ def go_to_dashboard_refresh(user):
 
 
843
  if not user:
844
+ return show_only(3)
845
+ return show_only(4)
846
+
847
+ nav_dashboard_btn.click(
848
+ go_to_dashboard_refresh, inputs=[current_user], outputs=ALL_VIEWS
 
 
 
 
 
 
 
 
 
849
  )
850
 
851
+ # =================================================================
852
+ # Dashboard wiring
853
+ # =================================================================
854
+ current_user.change(
855
+ load_dashboard, inputs=[current_user], outputs=[dash_welcome, usage_md]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
856
  )
857
 
858
+ upload_btn.click(
859
+ do_upload,
860
+ inputs=[upload_files, current_user],
861
+ outputs=[upload_status, upload_table, upload_json, usage_md],
862
+ )
863
 
864
+ refresh_invoices_btn.click(
865
+ refresh_invoices,
866
+ inputs=[current_user, invoices_filter],
867
+ outputs=[invoices_table],
868
+ )
869
+ invoices_filter.change(
870
+ refresh_invoices,
871
+ inputs=[current_user, invoices_filter],
872
+ outputs=[invoices_table],
873
+ )
874
 
875
+ delete_invoice_btn.click(
876
+ do_delete_invoice,
877
+ inputs=[current_user, delete_id_input],
878
+ outputs=[delete_status, invoices_table],
879
+ )
880
 
881
+ chat_send_btn.click(
882
+ chat_respond,
883
+ inputs=[chat_input, chatbot, current_user],
884
+ outputs=[chatbot, chat_input],
885
+ )
886
+ chat_input.submit(
887
+ chat_respond,
888
+ inputs=[chat_input, chatbot, current_user],
889
+ outputs=[chatbot, chat_input],
890
+ )
891
 
892
+ export_csv_btn.click(
893
+ export_csv, inputs=[current_user], outputs=[export_csv_file]
894
+ )
895
+ export_json_btn.click(
896
+ export_json, inputs=[current_user], outputs=[export_json_file]
897
+ )
898
 
899
+ upgrade_btn.click(
900
+ do_upgrade,
901
+ inputs=[upgrade_plan_dd, current_user],
902
+ outputs=[upgrade_link],
903
+ )
904
+ check_payment_btn.click(
905
+ do_check_payment,
906
+ inputs=[session_id_input, current_user],
907
+ outputs=[payment_status_md],
908
+ )
909
 
910
+ current_user.change(
911
+ load_api_tab,
912
+ inputs=[current_user],
913
+ outputs=[api_lock_msg, api_key_display, api_docs],
914
+ )
915
 
916
+ current_user.change(
917
+ load_profile, inputs=[current_user], outputs=[profile_info]
918
+ )
919
+ change_pw_btn.click(
920
+ do_change_password,
921
+ inputs=[current_user, new_password],
922
+ outputs=[change_pw_status],
923
+ )
924
+ delete_account_btn.click(
925
+ do_delete_account,
926
+ inputs=[current_user, session_token],
927
+ outputs=[delete_account_status, current_user, session_token],
928
+ )
929
 
 
 
930
 
931
+ # ---------------------------------------------------------------------------
932
+ # Launch
933
+ # ---------------------------------------------------------------------------
934
+ if __name__ == "__main__":
935
  demo.queue()
936
+ demo.launch()