simikkk commited on
Commit
d44e84f
·
verified ·
1 Parent(s): 1ec39d6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +357 -542
app.py CHANGED
@@ -223,7 +223,6 @@ def agent_chat(user_message: str, extracted_json: str) -> str:
223
  lines = [f"• **{k}**: {v}" for k, v in list(fields.items())[:10]]
224
  return "📋 **Extracted fields**:\n" + "\n".join(lines)
225
 
226
- # Fallback
227
  keys = list(fields.keys())[:6]
228
  return f"I have {len(fields)} fields extracted from this document. You can ask about: {', '.join(keys[:5])}{'...' if len(keys) > 5 else ''}."
229
 
@@ -231,21 +230,18 @@ def agent_chat(user_message: str, extracted_json: str) -> str:
231
  # ─── Gradio wrapper functions ───────────────────────────────────────────────
232
 
233
  def gr_parse(image_b64):
234
- """Called from JS via gr.Button — receives base64, returns JSON string."""
235
  return parse_invoice(image_b64)
236
 
237
  def gr_chat(user_msg, extracted_json):
238
- """Called from JS via gr.Button."""
239
  return agent_chat(user_msg, extracted_json)
240
 
241
 
242
- # ─── Custom CSS (minimal — real UI is HTML) ─────────────────────────────────
243
  CUSTOM_CSS = """
244
  body { margin: 0 !important; padding: 0 !important; background: #09090b !important; }
245
  .gradio-container { max-width: 100% !important; padding: 0 !important; margin: 0 !important; background: #09090b !important; }
246
  footer { display: none !important; }
247
  #omniparse-root { width: 100%; }
248
- /* Hide all default Gradio UI elements that we don't need */
249
  #hidden-controls { display: none !important; }
250
  """
251
 
@@ -284,7 +280,6 @@ body{font-family:'Inter',system-ui,sans-serif;background:var(--bg);color:var(--t
284
  ::-webkit-scrollbar-track{background:var(--surface2);}
285
  ::-webkit-scrollbar-thumb{background:var(--border2);border-radius:2px;}
286
 
287
- /* ── Animations ── */
288
  @keyframes spin{to{transform:rotate(360deg);}}
289
  @keyframes pulse{0%,100%{opacity:.4;}50%{opacity:1;}}
290
  @keyframes fadeUp{from{opacity:0;transform:translateY(8px);}to{opacity:1;transform:translateY(0);}}
@@ -304,16 +299,13 @@ body{font-family:'Inter',system-ui,sans-serif;background:var(--bg);color:var(--t
304
  .typing-dot:nth-child(3){animation-delay:.4s;}
305
  .glow-blue{animation:glow 2s ease-in-out infinite;}
306
 
307
- /* ── Layout ── */
308
  .card{background:var(--surface2);border:1px solid var(--border);border-radius:14px;}
309
  .card-inner{background:#1c1c1f;border:1px solid var(--border);border-radius:10px;}
310
  .section-label{font-size:10px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:var(--text4);}
311
 
312
- /* ── Drop Zone ── */
313
  .drop-zone{border:1.5px dashed var(--border2);border-radius:12px;transition:all .25s ease;cursor:pointer;}
314
  .drop-zone:hover,.drop-zone.drag-over{border-color:var(--blue);background:rgba(59,130,246,.05);box-shadow:0 0 0 4px rgba(59,130,246,.08),inset 0 0 24px rgba(59,130,246,.04);}
315
 
316
- /* ── Buttons ── */
317
  .btn-primary{background:linear-gradient(135deg,var(--blue) 0%,var(--blue-dark) 100%);color:#fff;border:none;border-radius:12px;font-weight:600;font-size:14px;cursor:pointer;transition:all .2s ease;box-shadow:0 0 20px rgba(59,130,246,.25);}
318
  .btn-primary:hover:not(:disabled){box-shadow:0 0 32px rgba(59,130,246,.45);transform:translateY(-1px);filter:brightness(1.08);}
319
  .btn-primary:active:not(:disabled){transform:translateY(0);}
@@ -321,12 +313,10 @@ body{font-family:'Inter',system-ui,sans-serif;background:var(--bg);color:var(--t
321
  .btn-secondary{background:var(--surface2);border:1px solid var(--border2);color:var(--text2);border-radius:8px;font-size:12px;font-weight:500;cursor:pointer;transition:all .18s ease;padding:6px 12px;}
322
  .btn-secondary:hover{border-color:var(--blue-light);color:var(--text);background:#1c1c1f;}
323
 
324
- /* ── Tabs ── */
325
  .tab-btn{font-size:12px;font-weight:500;padding:6px 12px;border-radius:6px;border:none;cursor:pointer;transition:all .18s ease;color:var(--text3);background:transparent;}
326
  .tab-btn.active{color:var(--text);background:var(--border);}
327
  .tab-btn:hover:not(.active){color:var(--text2);background:rgba(39,39,42,.5);}
328
 
329
- /* ── Chat ── */
330
  .bubble-user{background:var(--border);border:1px solid var(--border2);border-radius:14px 14px 4px 14px;}
331
  .bubble-ai{background:rgba(59,130,246,.07);border:1px solid rgba(59,130,246,.18);border-radius:14px 14px 14px 4px;}
332
  .ai-avatar{box-shadow:0 0 0 2px rgba(59,130,246,.3),0 0 12px rgba(59,130,246,.2);}
@@ -334,7 +324,6 @@ body{font-family:'Inter',system-ui,sans-serif;background:var(--bg);color:var(--t
334
  .chat-input:focus{border-color:var(--blue);box-shadow:0 0 0 3px rgba(59,130,246,.12);}
335
  .chat-input::placeholder{color:var(--text4);}
336
 
337
- /* ── Code ── */
338
  .code-view{background:#0d1117;border:1px solid #21262d;border-radius:10px;font-family:'JetBrains Mono','Fira Code',ui-monospace,monospace;}
339
  .json-key{color:#79c0ff;}
340
  .json-string{color:#a5d6ff;}
@@ -343,32 +332,17 @@ body{font-family:'Inter',system-ui,sans-serif;background:var(--bg);color:var(--t
343
  .json-null{color:#8b949e;}
344
  pre.json-pre{white-space:pre-wrap;word-break:break-word;font-size:12.5px;line-height:1.75;}
345
 
346
- /* ── Download cards ── */
347
  .dl-card{background:linear-gradient(135deg,rgba(59,130,246,.07) 0%,rgba(29,78,216,.04) 100%);border:1px solid rgba(59,130,246,.2);border-radius:12px;transition:all .2s ease;}
348
  .dl-card:hover{border-color:rgba(59,130,246,.4);background:linear-gradient(135deg,rgba(59,130,246,.1) 0%,rgba(29,78,216,.08) 100%);}
349
-
350
- /* ── Toast ── */
351
  .toast{animation:slideIn .3s ease;}
352
  .toast.hide{animation:slideOut .3s ease forwards;}
353
-
354
- /* ── Stat chip ── */
355
  .stat-chip{background:var(--surface2);border:1px solid var(--border);border-radius:10px;padding:12px 16px;}
356
-
357
- /* ── Progress ── */
358
  .prog-track{background:var(--border);border-radius:4px;height:3px;}
359
  .prog-fill{height:3px;border-radius:4px;background:linear-gradient(90deg,var(--blue),#6366f1);transition:width .4s ease;}
360
-
361
- /* ── Gradient text ── */
362
  .grad{background:linear-gradient(135deg,#60a5fa,#a78bfa);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;}
363
-
364
- /* ── Shimmer ── */
365
  .shimmer{background:linear-gradient(90deg,#27272a 25%,#3f3f46 50%,#27272a 75%);background-size:800px 100%;animation:shimmer 1.8s infinite;}
366
-
367
- /* ── File item ── */
368
  .file-item{background:#1c1c1f;border:1px solid var(--border);border-radius:8px;transition:border-color .18s;}
369
  .file-item:hover{border-color:var(--border2);}
370
-
371
- /* ── Stage indicator ── */
372
  .stage-dot{width:8px;height:8px;border-radius:50%;background:var(--border2);transition:background .3s ease;}
373
  .stage-dot.active{background:var(--blue);animation:pulse 1.4s ease-in-out infinite;}
374
  .stage-dot.done{background:var(--green);animation:none;}
@@ -376,10 +350,8 @@ pre.json-pre{white-space:pre-wrap;word-break:break-word;font-size:12.5px;line-he
376
  </head>
377
  <body>
378
 
379
- <!-- Toast container -->
380
  <div id="toast-root" style="position:fixed;top:16px;right:16px;z-index:9999;display:flex;flex-direction:column;gap:8px;"></div>
381
 
382
- <!-- ═══ HEADER ═══ -->
383
  <header style="position:sticky;top:0;z-index:40;border-bottom:1px solid var(--border);background:rgba(9,9,11,.92);backdrop-filter:blur(16px);">
384
  <div style="max-width:1280px;margin:0 auto;padding:0 24px;height:56px;display:flex;align-items:center;justify-content:space-between;">
385
  <div style="display:flex;align-items:center;gap:12px;">
@@ -402,10 +374,8 @@ pre.json-pre{white-space:pre-wrap;word-break:break-word;font-size:12.5px;line-he
402
  </div>
403
  </header>
404
 
405
- <!-- ═══ MAIN ═══ -->
406
  <main style="max-width:1280px;margin:0 auto;padding:24px;">
407
 
408
- <!-- Stats bar -->
409
  <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:20px;" id="stats-bar">
410
  <div class="stat-chip" style="display:flex;align-items:center;gap:12px;">
411
  <div style="width:32px;height:32px;border-radius:8px;background:rgba(59,130,246,.1);border:1px solid rgba(59,130,246,.2);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
@@ -433,13 +403,9 @@ pre.json-pre{white-space:pre-wrap;word-break:break-word;font-size:12.5px;line-he
433
  </div>
434
  </div>
435
 
436
- <!-- Two-column layout -->
437
  <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
438
 
439
- <!-- ═══ LEFT ═══ -->
440
  <div style="display:flex;flex-direction:column;gap:16px;">
441
-
442
- <!-- Upload Card -->
443
  <div class="card" style="padding:20px;">
444
  <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
445
  <div>
@@ -469,17 +435,12 @@ pre.json-pre{white-space:pre-wrap;word-break:break-word;font-size:12.5px;line-he
469
  <span style="padding:2px 8px;border-radius:4px;font-size:10px;font-weight:500;color:var(--text3);background:var(--border);">TIFF</span>
470
  </div>
471
  </div>
472
-
473
- <!-- Preview -->
474
  <div id="file-preview" style="margin-top:12px;display:none;">
475
  <img id="img-preview" style="width:100%;max-height:200px;object-fit:contain;border-radius:8px;border:1px solid var(--border);"/>
476
  </div>
477
-
478
- <!-- File list -->
479
  <div id="file-list" style="margin-top:10px;display:flex;flex-direction:column;gap:8px;"></div>
480
  </div>
481
 
482
- <!-- Execute Card -->
483
  <div class="card" style="padding:16px;">
484
  <button id="exec-btn" class="btn-primary" style="width:100%;padding:14px;display:flex;align-items:center;justify-content:center;gap:10px;" disabled onclick="executeExtraction()">
485
  <span id="btn-idle" style="display:flex;align-items:center;gap:8px;">
@@ -491,582 +452,437 @@ pre.json-pre{white-space:pre-wrap;word-break:break-word;font-size:12.5px;line-he
491
  Processing…
492
  </span>
493
  </button>
494
-
495
- <!-- Progress -->
496
  <div id="prog-wrapper" style="display:none;margin-top:14px;">
497
  <div style="display:flex;justify-content:space-between;margin-bottom:6px;">
498
- <span id="prog-label" style="font-size:12px;color:var(--text4);">Initializing…</span>
499
- <span id="prog-pct" style="font-size:12px;color:var(--text2);font-family:'JetBrains Mono',monospace;">0%</span>
500
- </div>
501
- <div class="prog-track"><div id="prog-fill" class="prog-fill" style="width:0%;"></div></div>
502
- </div>
503
-
504
- <!-- Stages -->
505
- <div id="stages" style="display:none;margin-top:14px;display:none;grid-template-columns:1fr 1fr 1fr;gap:8px;">
506
- <div style="text-align:center;padding:10px 8px;border-radius:8px;background:var(--border);">
507
- <div id="s1-dot" class="stage-dot" style="margin:0 auto 6px;"></div>
508
- <p style="font-size:10px;color:var(--text4);">OCR Scan</p>
509
  </div>
510
- <div style="text-align:center;padding:10px 8px;border-radius:8px;background:var(--border);">
511
- <div id="s2-dot" class="stage-dot" style="margin:0 auto 6px;"></div>
512
- <p style="font-size:10px;color:var(--text4);">AI Parsing</p>
513
  </div>
514
- <div style="text-align:center;padding:10px 8px;border-radius:8px;background:var(--border);">
515
- <div id="s3-dot" class="stage-dot" style="margin:0 auto 6px;"></div>
516
- <p style="font-size:10px;color:var(--text4);">Structuring</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517
  </div>
518
  </div>
519
  </div>
 
520
 
521
- <!-- Export Card -->
522
- <div class="card" style="padding:20px;">
523
- <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
524
- <div>
525
- <p style="font-size:14px;font-weight:600;">Export Results</p>
526
- <p style="font-size:12px;color:var(--text4);margin-top:2px;">Download structured data</p>
527
  </div>
528
- <span class="section-label">Stage 03</span>
529
  </div>
530
 
531
- <div id="export-empty" style="border-radius:10px;padding:24px;display:flex;flex-direction:column;align-items:center;gap:10px;text-align:center;background:#1c1c1f;border:1px dashed var(--border);">
532
- <div style="width:40px;height:40px;border-radius:8px;background:var(--border);display:flex;align-items:center;justify-content:center;">
533
- <svg width="18" height="18" fill="none" viewBox="0 0 24 24" stroke="var(--text4)" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"/></svg>
 
 
534
  </div>
535
- <p style="font-size:12px;color:var(--text4);">Run extraction to generate export files</p>
536
- </div>
537
 
538
- <div id="export-ready" style="display:none;flex-direction:column;gap:10px;">
539
- <div class="dl-card" style="padding:14px;display:flex;align-items:center;justify-content:space-between;gap:12px;">
540
- <div style="display:flex;align-items:center;gap:12px;">
541
- <div style="width:36px;height:36px;border-radius:8px;background:rgba(59,130,246,.15);border:1px solid rgba(59,130,246,.25);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
542
- <svg width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="#60a5fa" stroke-width="1.8"><path d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5.586a1 1 0 0 1 .707.293l5.414 5.414a1 1 0 0 1 .293.707V19a2 2 0 0 1-2 2z"/></svg>
 
 
 
 
 
 
 
543
  </div>
544
- <div>
545
- <p style="font-size:14px;font-weight:500;" id="dl-filename">parsed_data.csv</p>
546
- <p style="font-size:11px;color:var(--text4);" id="dl-meta">Ready to download</p>
 
 
 
547
  </div>
548
  </div>
549
- <a id="dl-csv" href="#" download="parsed_data.csv" style="padding:6px 12px;border-radius:8px;font-size:12px;font-weight:600;background:rgba(59,130,246,.12);border:1px solid rgba(59,130,246,.3);color:#60a5fa;text-decoration:none;display:flex;align-items:center;gap:6px;">
550
- <svg width="12" height="12" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"/></svg>
551
- CSV
552
- </a>
553
  </div>
554
  </div>
555
- </div>
556
 
557
- </div><!-- /left -->
558
-
559
- <!-- ═══ RIGHT ═══ -->
560
- <div class="card" style="display:flex;flex-direction:column;min-height:680px;">
561
-
562
- <!-- Tab header -->
563
- <div style="padding:14px 16px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;">
564
- <div style="display:flex;align-items:center;gap:4px;padding:4px;border-radius:8px;background:#0f0f11;">
565
- <button class="tab-btn active" id="tab-chat" onclick="switchTab('chat',this)">
566
- <span style="display:flex;align-items:center;gap:6px;">
567
- <svg width="12" height="12" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 0 1-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/></svg>
568
- Invoice AI Agent
569
- </span>
570
- </button>
571
- <button class="tab-btn" id="tab-json" onclick="switchTab('json',this)">
572
- <span style="display:flex;align-items:center;gap:6px;">
573
- <svg width="12" height="12" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M14.25 9.75 16.5 12l-2.25 2.25m-4.5 0L7.5 12l2.25-2.25M6 20.25h12A2.25 2.25 0 0 0 20.25 18V6A2.25 2.25 0 0 0 18 3.75H6A2.25 2.25 0 0 0 3.75 6v12A2.25 2.25 0 0 0 6 20.25z"/></svg>
574
- Developer JSON
575
- </span>
576
- </button>
577
- </div>
578
- <div style="display:flex;align-items:center;gap:8px;">
579
- <span style="font-size:10px;font-weight:500;padding:2px 8px;border-radius:20px;background:rgba(52,211,153,.1);border:1px solid rgba(52,211,153,.2);color:#34d399;">● Online</span>
580
- <button onclick="clearChat()" class="btn-secondary" style="padding:4px 8px;" title="Clear chat">
581
- <svg width="13" height="13" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="m19 7-.867 12.142A2 2 0 0 1 16.138 21H7.862a2 2 0 0 1-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v3M4 7h16"/></svg>
582
- </button>
583
- </div>
584
- </div>
585
-
586
- <!-- Chat panel -->
587
- <div id="panel-chat" style="display:flex;flex-direction:column;flex:1;">
588
- <div id="chat-messages" style="flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px;min-height:380px;max-height:440px;">
589
- <div class="fade-up" style="display:flex;align-items:flex-start;gap:10px;">
590
- <div class="ai-avatar" style="width:28px;height:28px;border-radius:8px;background:linear-gradient(135deg,#3b82f6,#1d4ed8);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
591
- <svg width="13" height="13" fill="none" viewBox="0 0 24 24" stroke="white" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>
592
- </div>
593
- <div class="bubble-ai" style="padding:10px 14px;max-width:85%;">
594
- <p style="font-size:10px;color:#60a5fa;font-weight:600;margin-bottom:4px;">OmniParse Agent</p>
595
- <p style="font-size:13px;color:var(--text);line-height:1.6;">Hello! I'm your Invoice AI Agent. Upload a document and run extraction — then ask me anything about the parsed data: totals, vendors, line items, validation status.</p>
596
  </div>
597
  </div>
598
- </div>
599
 
600
- <!-- Chat input -->
601
- <div style="padding:14px;border-top:1px solid var(--border);">
602
- <div style="display:flex;align-items:flex-end;gap:8px;">
603
- <textarea id="chat-input" class="chat-input" rows="1" placeholder="Ask about totals, vendor, date, confidence score…"
604
- onkeydown="handleKey(event)" oninput="autoSize(this)"></textarea>
605
- <button class="btn-primary" style="padding:8px 16px;border-radius:10px;font-size:13px;white-space:nowrap;flex-shrink:0;height:38px;display:flex;align-items:center;gap:6px;" onclick="sendChat()">
606
- <svg width="13" height="13" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M6 12 3.269 3.125A59.769 59.769 0 0 1 21.485 12 59.768 59.768 0 0 1 3.27 20.875L5.999 12zm0 0h7.5"/></svg>
607
- Send
608
  </button>
609
  </div>
610
- <p style="font-size:10px;color:var(--text4);margin-top:6px;">Ctrl+Enter to send · Agent reads extracted document context</p>
611
- </div>
612
- </div>
613
-
614
- <!-- JSON panel -->
615
- <div id="panel-json" style="display:none;flex-direction:column;flex:1;padding:16px;">
616
- <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;">
617
- <div style="display:flex;align-items:center;gap:8px;">
618
- <span style="width:12px;height:12px;border-radius:50%;background:#f87171;opacity:.7;"></span>
619
- <span style="width:12px;height:12px;border-radius:50%;background:#fbbf24;opacity:.7;"></span>
620
- <span style="width:12px;height:12px;border-radius:50%;background:#34d399;opacity:.7;"></span>
621
- <span style="font-size:12px;color:var(--text4);font-family:'JetBrains Mono',monospace;margin-left:4px;">parsed_output.json</span>
622
- </div>
623
- <div style="display:flex;gap:6px;">
624
- <button class="btn-secondary" onclick="copyJSON()" id="copy-btn">
625
- <svg width="12" height="12" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
626
- Copy
627
- </button>
628
- </div>
629
- </div>
630
- <div class="code-view" style="flex:1;overflow:auto;padding:16px;max-height:520px;min-height:380px;">
631
- <pre class="json-pre" id="json-out"><span style="color:#8b949e;">// Waiting for extraction result…
632
- // Run "Execute Document Extraction" to see structured JSON here.</span></pre>
633
  </div>
634
  </div>
635
-
636
- </div><!-- /right -->
637
- </div><!-- /grid -->
638
-
639
- <!-- Footer -->
640
- <footer style="margin-top:32px;padding-top:20px;border-top:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;font-size:11px;color:var(--text4);">
641
- <span>OmniParse AI · Enterprise Terminal v5.0 · © 2025</span>
642
- <div style="display:flex;align-items:center;gap:16px;">
643
- <span>Model: <span style="color:var(--text3);">donut-cord-v2</span></span>
644
- <span id="footer-latency">Latency: —</span>
645
- <span style="display:flex;align-items:center;gap:6px;">
646
- <span style="width:6px;height:6px;border-radius:50%;background:#34d399;box-shadow:0 0 4px #34d399;"></span>
647
- All systems operational
648
- </span>
649
  </div>
650
- </footer>
651
 
 
652
  </main>
653
 
654
- <!-- ═══ SCRIPT ═══ -->
655
  <script>
656
- // ─── State ───────────────────────────────────────────────────────────────────
657
- const S = {
658
- files: [],
659
- imageB64: null,
660
- extractedJSON: null,
661
- chatJSON: "",
662
- processing: false,
663
- docsCount: 0,
664
- fieldsCount: 0,
665
- };
666
-
667
- // ─── Drag & Drop ─────────────────────────────────────────────────────────────
668
- function handleDrop(e) {
669
- e.preventDefault();
670
- document.getElementById('drop-zone').classList.remove('drag-over');
671
- handleFiles(e.dataTransfer.files);
 
 
672
  }
673
 
674
- function handleFiles(fileList) {
675
- const files = Array.from(fileList);
676
- if (!files.length) return;
677
- S.files = [...S.files, ...files];
678
- renderFileList();
679
- // Read first image for preview + base64
680
- const imgFile = files.find(f => f.type.startsWith('image/') || f.name.match(/\.(jpg|jpeg|png|webp|tiff)$/i));
681
- if (imgFile) {
682
- const reader = new FileReader();
683
- reader.onload = (ev) => {
684
- S.imageB64 = ev.target.result;
685
- document.getElementById('img-preview').src = ev.target.result;
686
- document.getElementById('file-preview').style.display = 'block';
687
- };
688
- reader.readAsDataURL(imgFile);
689
- } else if (files[0].type === 'application/pdf') {
690
- // PDF placeholder
691
- S.imageB64 = null;
692
- document.getElementById('file-preview').style.display = 'none';
693
- showToast('PDF uploaded — note: Donut model works best with image formats.', 'amber');
694
  }
695
- document.getElementById('exec-btn').disabled = false;
696
- showToast('File added — ready to extract', 'success');
697
  }
698
 
699
- function renderFileList() {
700
- const list = document.getElementById('file-list');
701
- list.innerHTML = '';
702
- S.files.forEach((f, i) => {
703
- const ext = f.name.split('.').pop().toUpperCase();
704
- const kb = (f.size / 1024).toFixed(1);
705
- const el = document.createElement('div');
706
- el.className = 'file-item';
707
- el.style.cssText = 'display:flex;align-items:center;gap:10px;padding:8px 12px;';
708
- el.innerHTML = `
709
- <div style="width:28px;height:28px;border-radius:6px;background:var(--border);display:flex;align-items:center;justify-content:center;font-size:9px;font-weight:700;color:var(--text3);flex-shrink:0;">${ext}</div>
710
- <div style="flex:1;min-width:0;">
711
- <p style="font-size:12px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${f.name}</p>
712
- <p style="font-size:10px;color:var(--text4);">${kb} KB</p>
713
  </div>
714
- <button onclick="removeFile(${i})" style="background:none;border:none;cursor:pointer;color:var(--text4);padding:4px;" title="Remove">
715
- <svg width="12" height="12" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path d="M18 6 6 18M6 6l12 12"/></svg>
716
- </button>`;
717
- list.appendChild(el);
718
- });
719
- }
720
-
721
- function removeFile(idx) {
722
- S.files.splice(idx, 1);
723
- if (!S.files.length) {
724
- document.getElementById('exec-btn').disabled = true;
725
- document.getElementById('file-preview').style.display = 'none';
726
- S.imageB64 = null;
727
- }
728
- renderFileList();
729
- }
730
-
731
- // ─── Execute Extraction ───────────────────────────────────────────────────────
732
- async function executeExtraction() {
733
- if (S.processing || !S.files.length) return;
734
- if (!S.imageB64) {
735
- showToast('Image preview required. Use JPG/PNG/WEBP format.', 'amber');
736
- // Still proceed with Gradio call — backend may handle PDF too
737
- }
738
- S.processing = true;
739
- setProcessingUI(true);
740
- setStatus('Processing', 'amber');
741
-
742
- // Animate stages
743
- animateStage(1, 'Running OCR scan…', 25);
744
- setTimeout(() => animateStage(2, 'AI parsing fields…', 55), 1000);
745
- setTimeout(() => animateStage(3, 'Structuring output…', 85), 2200);
746
-
747
- try {
748
- // Call Gradio backend via the hidden textarea bridge
749
- const payload = S.imageB64 || "";
750
- const result = await callGradioFn('parse_fn', payload);
751
- handleExtractionResult(result);
752
- } catch (err) {
753
- handleExtractionError("Network or backend error: " + err.message);
754
- }
755
  }
756
 
757
- // Bridge to Gradio Python backend
758
- async function callGradioFn(fnId, payload) {
759
- // We communicate via hidden Gradio components
760
- const inputEl = document.querySelector('#gr-image-input textarea');
761
- const submitEl = document.querySelector('#gr-parse-btn');
762
- if (inputEl && submitEl) {
763
- inputEl.value = payload;
764
- inputEl.dispatchEvent(new Event('input', { bubbles: true }));
765
- submitEl.click();
 
 
 
 
 
766
  }
767
- // Wait for result via polling the output element
768
- return new Promise((resolve, reject) => {
769
- let attempts = 0;
770
- const poll = setInterval(() => {
771
- attempts++;
772
- const outEl = document.querySelector('#gr-json-output textarea');
773
- if (outEl && outEl.value && outEl.value.length > 2) {
774
- clearInterval(poll);
775
- resolve(outEl.value);
776
- outEl.value = "";
777
- }
778
- if (attempts > 120) {
779
- clearInterval(poll);
780
- reject(new Error("Timeout waiting for backend response (60s)"));
781
- }
782
- }, 500);
783
- });
784
- }
785
 
786
- async function callChatFn(userMsg) {
787
- const msgEl = document.querySelector('#gr-chat-msg textarea');
788
- const jsonEl = document.querySelector('#gr-chat-json textarea');
789
- const btnEl = document.querySelector('#gr-chat-btn');
790
- if (msgEl && jsonEl && btnEl) {
791
- msgEl.value = userMsg;
792
- msgEl.dispatchEvent(new Event('input', { bubbles: true }));
793
- jsonEl.value = S.chatJSON || "{}";
794
- jsonEl.dispatchEvent(new Event('input', { bubbles: true }));
795
- btnEl.click();
796
- }
797
- return new Promise((resolve, reject) => {
798
- let attempts = 0;
799
- const poll = setInterval(() => {
800
- attempts++;
801
- const outEl = document.querySelector('#gr-chat-out textarea');
802
- if (outEl && outEl.value) {
803
- clearInterval(poll);
804
- resolve(outEl.value);
805
- outEl.value = "";
806
- }
807
- if (attempts > 60) {
808
- clearInterval(poll);
809
- reject(new Error("Chat timeout"));
810
- }
811
- }, 500);
812
  });
813
  }
814
 
815
- function handleExtractionResult(jsonStr) {
816
- try {
817
- const data = JSON.parse(jsonStr);
818
- S.extractedJSON = data;
819
- S.chatJSON = jsonStr;
820
-
821
- if (data.parser_status === "ERROR") {
822
- handleExtractionError(data.error_log || "Unknown error");
823
- return;
 
 
 
824
  }
 
 
 
 
825
 
826
- // Stats
827
- S.docsCount++;
828
- const fields = data.extracted_data || {};
829
- S.fieldsCount += Object.keys(fields).length;
830
- document.getElementById('st-docs').textContent = S.docsCount;
831
- document.getElementById('st-fields').textContent = S.fieldsCount;
832
- document.getElementById('st-time').textContent = (data.parse_time_seconds || '—') + 's';
833
- const conf = data.security_and_compliance?.confidence_score;
834
- document.getElementById('st-conf').textContent = conf ? Math.round(conf * 100) + '%' : '—';
835
- document.getElementById('footer-latency').textContent = 'Latency: ' + (data.parse_time_seconds || '—') + 's';
836
-
837
- // JSON tab
838
- document.getElementById('json-out').innerHTML = syntaxHL(JSON.stringify(data, null, 2));
839
-
840
- // CSV download
841
- const csvB64 = data._csv_b64;
842
- if (csvB64) {
843
- const dlLink = document.getElementById('dl-csv');
844
- dlLink.href = 'data:text/csv;base64,' + csvB64;
845
- dlLink.download = 'omniparse_' + Date.now() + '.csv';
846
- document.getElementById('export-empty').style.display = 'none';
847
- document.getElementById('export-ready').style.display = 'flex';
848
- document.getElementById('dl-meta').textContent = 'Generated at ' + new Date().toLocaleTimeString();
849
  }
850
-
851
- finishStages();
852
- setProcessingUI(false);
853
- setStatus('Idle', 'green');
854
- S.processing = false;
855
-
856
- // Agent message
857
- const vendor = fields.STORE_NAME || fields.VENDOR || fields.COMPANY || 'the vendor';
858
- const total = fields.TOTAL || fields.TOTAL_PRICE || 'N/A';
859
- const dupFlag = data.security_and_compliance?.duplicate_detected;
860
- const valStatus = data.security_and_compliance?.cross_field_validation;
861
- let agentMsg = `✅ **Extraction complete!**\n\n• Vendor: **${vendor}**\n• Total: **${total}**\n• Fields extracted: **${Object.keys(fields).length}**\n• Confidence: **${Math.round((conf || 0) * 100)}%**\n• Validation: **${valStatus || 'N/A'}**`;
862
- if (dupFlag) agentMsg += '\n\n⚠️ **Warning:** This document appears to be a duplicate!';
863
- addMsg('agent', agentMsg);
864
- showToast('Extraction complete', 'success');
865
- } catch (e) {
866
- handleExtractionError("Failed to parse backend response: " + e.message);
867
- }
868
  }
869
 
870
- function handleExtractionError(msg) {
871
- setProcessingUI(false);
872
- setStatus('Error', 'red');
873
- S.processing = false;
874
- addMsg('agent', '❌ **Extraction failed:** ' + msg);
875
- showToast('Extraction failed — see chat for details', 'error');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
876
  }
877
 
878
- function animateStage(id, label, pct) {
879
- document.getElementById('prog-label').textContent = label;
880
- document.getElementById('prog-fill').style.width = pct + '%';
881
- document.getElementById('prog-pct').textContent = pct + '%';
882
- for (let j = 1; j <= 3; j++) {
883
- const dot = document.getElementById(`s${j}-dot`);
884
- dot.className = 'stage-dot' + (j < id ? ' done' : j === id ? ' active' : '');
885
- }
 
 
886
  }
887
 
888
- function finishStages() {
889
- for (let j = 1; j <= 3; j++) document.getElementById(`s${j}-dot`).className = 'stage-dot done';
890
- document.getElementById('prog-fill').style.width = '100%';
891
- document.getElementById('prog-pct').textContent = '100%';
892
- document.getElementById('prog-label').textContent = 'Complete ✓';
 
 
 
 
 
 
 
 
 
 
 
 
 
893
  }
894
 
895
- // ─── Chat ─────────────────────────────────────────────────────────────────────
896
- async function sendChat() {
897
- const input = document.getElementById('chat-input');
898
- const text = input.value.trim();
899
- if (!text) return;
900
- addMsg('user', text);
901
- input.value = '';
902
- input.style.height = 'auto';
903
- showTyping();
904
-
905
- try {
906
- const reply = await callChatFn(text);
907
- addMsg('agent', reply || "I couldn't generate a response. Please try again.");
908
- } catch (e) {
909
- // Fallback client-side response
910
- const fb = clientFallback(text);
911
- addMsg('agent', fb);
912
  }
913
  }
914
 
915
- function clientFallback(text) {
916
- if (!S.extractedJSON) return "Please run document extraction first.";
917
- const fields = S.extractedJSON.extracted_data || {};
918
- const msg = text.toLowerCase();
919
- if (msg.includes('total')) return `💰 Total: **${fields.TOTAL || fields.TOTAL_PRICE || 'not found'}**`;
920
- if (msg.includes('vendor') || msg.includes('company')) return `🏢 Vendor: **${fields.STORE_NAME || fields.VENDOR || 'not found'}**`;
921
- if (msg.includes('date')) return `📅 Date: **${fields.DATE || 'not found'}**`;
922
- const conf = S.extractedJSON.security_and_compliance?.confidence_score;
923
- if (msg.includes('confidence')) return `🎯 Confidence: **${conf ? Math.round(conf*100)+'%' : 'N/A'}**`;
924
- const lines = Object.entries(fields).slice(0, 6).map(([k,v]) => `• **${k}**: ${v}`).join('\n');
925
- return `📋 Extracted fields:\n${lines}`;
926
- }
927
-
928
- function handleKey(e) {
929
- if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); sendChat(); }
930
- }
931
-
932
- function autoSize(el) {
933
- el.style.height = 'auto';
934
- el.style.height = Math.min(el.scrollHeight, 120) + 'px';
935
- }
936
-
937
- function addMsg(sender, text) {
938
- const container = document.getElementById('chat-messages');
939
- document.getElementById('typing-ind')?.remove();
940
- const isUser = sender === 'user';
941
- const el = document.createElement('div');
942
- el.className = 'fade-up';
943
- el.style.cssText = `display:flex;align-items:flex-start;gap:10px;${isUser ? 'flex-direction:row-reverse;' : ''}`;
944
- const html = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>').replace(/\n/g, '<br>');
945
- if (isUser) {
946
- el.innerHTML = `
947
- <div style="width:28px;height:28px;border-radius:8px;background:rgba(59,130,246,.15);border:1px solid rgba(59,130,246,.2);display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:600;color:#93c5fd;flex-shrink:0;">U</div>
948
- <div class="bubble-user" style="padding:10px 14px;max-width:85%;"><p style="font-size:13px;line-height:1.6;">${html}</p></div>`;
949
- } else {
950
- el.innerHTML = `
951
- <div class="ai-avatar" style="width:28px;height:28px;border-radius:8px;background:linear-gradient(135deg,#3b82f6,#1d4ed8);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
952
- <svg width="13" height="13" fill="none" viewBox="0 0 24 24" stroke="white" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>
953
- </div>
954
- <div class="bubble-ai" style="padding:10px 14px;max-width:85%;">
955
- <p style="font-size:10px;color:#60a5fa;font-weight:600;margin-bottom:4px;">OmniParse Agent</p>
956
- <p style="font-size:13px;line-height:1.6;">${html}</p>
957
- </div>`;
958
  }
959
- container.appendChild(el);
960
- container.scrollTop = container.scrollHeight;
961
  }
962
 
963
- function showTyping() {
964
- const container = document.getElementById('chat-messages');
965
- const el = document.createElement('div');
966
- el.id = 'typing-ind';
967
- el.style.cssText = 'display:flex;align-items:flex-start;gap:10px;';
968
- el.innerHTML = `
969
- <div class="ai-avatar" style="width:28px;height:28px;border-radius:8px;background:linear-gradient(135deg,#3b82f6,#1d4ed8);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
970
- <svg width="13" height="13" fill="none" viewBox="0 0 24 24" stroke="white" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M12 1v2M12 21v2"/></svg>
 
 
 
 
 
 
971
  </div>
972
- <div class="bubble-ai" style="padding:12px 16px;">
973
- <div style="display:flex;align-items:center;gap:4px;">
974
- <span class="w-1.5 h-1.5 rounded-full typing-dot" style="width:6px;height:6px;border-radius:50%;background:#60a5fa;display:inline-block;"></span>
975
- <span class="typing-dot" style="width:6px;height:6px;border-radius:50%;background:#60a5fa;display:inline-block;animation-delay:.2s;"></span>
976
- <span class="typing-dot" style="width:6px;height:6px;border-radius:50%;background:#60a5fa;display:inline-block;animation-delay:.4s;"></span>
977
- </div>
978
- </div>`;
979
- container.appendChild(el);
980
- container.scrollTop = container.scrollHeight;
981
- }
982
-
983
- function clearChat() {
984
- document.getElementById('chat-messages').innerHTML = '';
985
- addMsg('agent', 'Chat cleared. Upload a document and extract to start a new session.');
986
- }
987
-
988
- // ─── Tabs ─────────────────────────────────────────────────────────────────────
989
- function switchTab(tab, btn) {
990
- ['chat','json'].forEach(t => {
991
- document.getElementById(`panel-${t}`).style.display = 'none';
992
- document.getElementById(`tab-${t}`).classList.remove('active');
993
- });
994
- document.getElementById(`panel-${tab}`).style.display = 'flex';
995
- btn.classList.add('active');
996
- }
997
-
998
- // ─── UI helpers ───────────────────────────────────────────────────────────────
999
- function setProcessingUI(on) {
1000
- document.getElementById('exec-btn').disabled = on;
1001
- document.getElementById('btn-idle').style.display = on ? 'none' : 'flex';
1002
- document.getElementById('btn-loading').style.display = on ? 'flex' : 'none';
1003
- document.getElementById('prog-wrapper').style.display = on ? 'block' : 'none';
1004
- document.getElementById('stages').style.display = on ? 'grid' : 'none';
1005
- if (on) {
1006
- document.getElementById('prog-fill').style.width = '5%';
1007
- document.getElementById('prog-pct').textContent = '5%';
1008
- document.getElementById('prog-label').textContent = 'Initializing engine…';
1009
  }
1010
  }
1011
 
1012
- function setStatus(text, color) {
1013
- const dot = document.getElementById('status-dot');
1014
- const label = document.getElementById('status-text');
1015
- label.textContent = 'System ' + text;
1016
- const map = { green: ['#34d399','#34d399'], amber: ['#fbbf24','#fbbf24'], red: ['#f87171','#f87171'] };
1017
- dot.style.background = map[color][0];
1018
- dot.style.boxShadow = `0 0 6px ${map[color][1]}`;
1019
- }
1020
-
1021
- function syntaxHL(json) {
1022
- return json
1023
- .replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')
1024
- .replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, match => {
1025
- let cls = 'json-number';
1026
- if (/^"/.test(match)) cls = /:$/.test(match) ? 'json-key' : 'json-string';
1027
- else if (/true|false/.test(match)) cls = 'json-bool';
1028
- else if (/null/.test(match)) cls = 'json-null';
1029
- return `<span class="${cls}">${match}</span>`;
1030
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1031
  }
1032
 
1033
- function copyJSON() {
1034
- if (!S.extractedJSON) { showToast('No JSON to copy', 'error'); return; }
1035
- navigator.clipboard.writeText(JSON.stringify(S.extractedJSON, null, 2)).then(() => {
1036
- const btn = document.getElementById('copy-btn');
1037
- btn.innerHTML = `<svg width="12" height="12" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> Copied!`;
1038
- btn.style.color = '#34d399';
1039
- setTimeout(() => { btn.innerHTML = `<svg width="12" height="12" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg> Copy`; btn.style.color = ''; }, 2000);
1040
- });
1041
  }
1042
 
1043
- // ─── Toast ────────────────────────────────────────────────────────────────────
1044
- function showToast(msg, type) {
1045
- const colors = {
1046
- success: { bg:'rgba(52,211,153,.1)', border:'rgba(52,211,153,.25)', icon:'<polyline points="20 6 9 17 4 12"/>' },
1047
- error: { bg:'rgba(248,113,113,.1)', border:'rgba(248,113,113,.25)', icon:'<path d="M18 6 6 18M6 6l12 12"/>' },
1048
- info: { bg:'rgba(59,130,246,.1)', border:'rgba(59,130,246,.25)', icon:'<circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/>' },
1049
- amber: { bg:'rgba(251,191,36,.1)', border:'rgba(251,191,36,.2)', icon:'<path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>' },
1050
- };
1051
- const c = colors[type] || colors.info;
1052
- const el = document.createElement('div');
1053
- el.className = 'toast';
1054
- el.style.cssText = `display:flex;align-items:center;gap:10px;padding:10px 16px;border-radius:12px;font-size:13px;font-weight:500;background:${c.bg};border:1px solid ${c.border};color:var(--text);min-width:220px;max-width:320px;`;
1055
- el.innerHTML = `<svg width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">${c.icon}</svg><span>${msg}</span>`;
1056
- document.getElementById('toast-root').appendChild(el);
1057
- setTimeout(() => { el.classList.add('hide'); setTimeout(() => el.remove(), 350); }, 3200);
1058
  }
1059
  </script>
 
1060
  </html>
1061
  """
1062
 
1063
- # ─── Build Gradio App ────────────────────────────────────────────────────────
1064
- with gr.Blocks(css=CUSTOM_CSS, title="OmniParse AI — Enterprise Terminal v5.0") as app:
1065
-
1066
- # Visible custom UI
1067
  gr.HTML(HTML_UI)
1068
 
1069
- # Hidden bridge controls — JS communicates through these
1070
  with gr.Row(elem_id="hidden-controls", visible=False):
1071
  with gr.Column():
1072
  gr_image_input = gr.Textbox(
@@ -1098,7 +914,6 @@ with gr.Blocks(css=CUSTOM_CSS, title="OmniParse AI — Enterprise Terminal v5.0"
1098
  visible=False,
1099
  )
1100
 
1101
- # Wire up events
1102
  gr_parse_btn.click(
1103
  fn=gr_parse,
1104
  inputs=[gr_image_input],
@@ -1112,4 +927,4 @@ with gr.Blocks(css=CUSTOM_CSS, title="OmniParse AI — Enterprise Terminal v5.0"
1112
  )
1113
 
1114
  if __name__ == "__main__":
1115
- app.launch(server_name="0.0.0.0", server_port=7860)
 
223
  lines = [f"• **{k}**: {v}" for k, v in list(fields.items())[:10]]
224
  return "📋 **Extracted fields**:\n" + "\n".join(lines)
225
 
 
226
  keys = list(fields.keys())[:6]
227
  return f"I have {len(fields)} fields extracted from this document. You can ask about: {', '.join(keys[:5])}{'...' if len(keys) > 5 else ''}."
228
 
 
230
  # ─── Gradio wrapper functions ───────────────────────────────────────────────
231
 
232
  def gr_parse(image_b64):
 
233
  return parse_invoice(image_b64)
234
 
235
  def gr_chat(user_msg, extracted_json):
 
236
  return agent_chat(user_msg, extracted_json)
237
 
238
 
239
+ # ─── Custom CSS ─────────────────────────────────────────────────────────────
240
  CUSTOM_CSS = """
241
  body { margin: 0 !important; padding: 0 !important; background: #09090b !important; }
242
  .gradio-container { max-width: 100% !important; padding: 0 !important; margin: 0 !important; background: #09090b !important; }
243
  footer { display: none !important; }
244
  #omniparse-root { width: 100%; }
 
245
  #hidden-controls { display: none !important; }
246
  """
247
 
 
280
  ::-webkit-scrollbar-track{background:var(--surface2);}
281
  ::-webkit-scrollbar-thumb{background:var(--border2);border-radius:2px;}
282
 
 
283
  @keyframes spin{to{transform:rotate(360deg);}}
284
  @keyframes pulse{0%,100%{opacity:.4;}50%{opacity:1;}}
285
  @keyframes fadeUp{from{opacity:0;transform:translateY(8px);}to{opacity:1;transform:translateY(0);}}
 
299
  .typing-dot:nth-child(3){animation-delay:.4s;}
300
  .glow-blue{animation:glow 2s ease-in-out infinite;}
301
 
 
302
  .card{background:var(--surface2);border:1px solid var(--border);border-radius:14px;}
303
  .card-inner{background:#1c1c1f;border:1px solid var(--border);border-radius:10px;}
304
  .section-label{font-size:10px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;color:var(--text4);}
305
 
 
306
  .drop-zone{border:1.5px dashed var(--border2);border-radius:12px;transition:all .25s ease;cursor:pointer;}
307
  .drop-zone:hover,.drop-zone.drag-over{border-color:var(--blue);background:rgba(59,130,246,.05);box-shadow:0 0 0 4px rgba(59,130,246,.08),inset 0 0 24px rgba(59,130,246,.04);}
308
 
 
309
  .btn-primary{background:linear-gradient(135deg,var(--blue) 0%,var(--blue-dark) 100%);color:#fff;border:none;border-radius:12px;font-weight:600;font-size:14px;cursor:pointer;transition:all .2s ease;box-shadow:0 0 20px rgba(59,130,246,.25);}
310
  .btn-primary:hover:not(:disabled){box-shadow:0 0 32px rgba(59,130,246,.45);transform:translateY(-1px);filter:brightness(1.08);}
311
  .btn-primary:active:not(:disabled){transform:translateY(0);}
 
313
  .btn-secondary{background:var(--surface2);border:1px solid var(--border2);color:var(--text2);border-radius:8px;font-size:12px;font-weight:500;cursor:pointer;transition:all .18s ease;padding:6px 12px;}
314
  .btn-secondary:hover{border-color:var(--blue-light);color:var(--text);background:#1c1c1f;}
315
 
 
316
  .tab-btn{font-size:12px;font-weight:500;padding:6px 12px;border-radius:6px;border:none;cursor:pointer;transition:all .18s ease;color:var(--text3);background:transparent;}
317
  .tab-btn.active{color:var(--text);background:var(--border);}
318
  .tab-btn:hover:not(.active){color:var(--text2);background:rgba(39,39,42,.5);}
319
 
 
320
  .bubble-user{background:var(--border);border:1px solid var(--border2);border-radius:14px 14px 4px 14px;}
321
  .bubble-ai{background:rgba(59,130,246,.07);border:1px solid rgba(59,130,246,.18);border-radius:14px 14px 14px 4px;}
322
  .ai-avatar{box-shadow:0 0 0 2px rgba(59,130,246,.3),0 0 12px rgba(59,130,246,.2);}
 
324
  .chat-input:focus{border-color:var(--blue);box-shadow:0 0 0 3px rgba(59,130,246,.12);}
325
  .chat-input::placeholder{color:var(--text4);}
326
 
 
327
  .code-view{background:#0d1117;border:1px solid #21262d;border-radius:10px;font-family:'JetBrains Mono','Fira Code',ui-monospace,monospace;}
328
  .json-key{color:#79c0ff;}
329
  .json-string{color:#a5d6ff;}
 
332
  .json-null{color:#8b949e;}
333
  pre.json-pre{white-space:pre-wrap;word-break:break-word;font-size:12.5px;line-height:1.75;}
334
 
 
335
  .dl-card{background:linear-gradient(135deg,rgba(59,130,246,.07) 0%,rgba(29,78,216,.04) 100%);border:1px solid rgba(59,130,246,.2);border-radius:12px;transition:all .2s ease;}
336
  .dl-card:hover{border-color:rgba(59,130,246,.4);background:linear-gradient(135deg,rgba(59,130,246,.1) 0%,rgba(29,78,216,.08) 100%);}
 
 
337
  .toast{animation:slideIn .3s ease;}
338
  .toast.hide{animation:slideOut .3s ease forwards;}
 
 
339
  .stat-chip{background:var(--surface2);border:1px solid var(--border);border-radius:10px;padding:12px 16px;}
 
 
340
  .prog-track{background:var(--border);border-radius:4px;height:3px;}
341
  .prog-fill{height:3px;border-radius:4px;background:linear-gradient(90deg,var(--blue),#6366f1);transition:width .4s ease;}
 
 
342
  .grad{background:linear-gradient(135deg,#60a5fa,#a78bfa);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;}
 
 
343
  .shimmer{background:linear-gradient(90deg,#27272a 25%,#3f3f46 50%,#27272a 75%);background-size:800px 100%;animation:shimmer 1.8s infinite;}
 
 
344
  .file-item{background:#1c1c1f;border:1px solid var(--border);border-radius:8px;transition:border-color .18s;}
345
  .file-item:hover{border-color:var(--border2);}
 
 
346
  .stage-dot{width:8px;height:8px;border-radius:50%;background:var(--border2);transition:background .3s ease;}
347
  .stage-dot.active{background:var(--blue);animation:pulse 1.4s ease-in-out infinite;}
348
  .stage-dot.done{background:var(--green);animation:none;}
 
350
  </head>
351
  <body>
352
 
 
353
  <div id="toast-root" style="position:fixed;top:16px;right:16px;z-index:9999;display:flex;flex-direction:column;gap:8px;"></div>
354
 
 
355
  <header style="position:sticky;top:0;z-index:40;border-bottom:1px solid var(--border);background:rgba(9,9,11,.92);backdrop-filter:blur(16px);">
356
  <div style="max-width:1280px;margin:0 auto;padding:0 24px;height:56px;display:flex;align-items:center;justify-content:space-between;">
357
  <div style="display:flex;align-items:center;gap:12px;">
 
374
  </div>
375
  </header>
376
 
 
377
  <main style="max-width:1280px;margin:0 auto;padding:24px;">
378
 
 
379
  <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:20px;" id="stats-bar">
380
  <div class="stat-chip" style="display:flex;align-items:center;gap:12px;">
381
  <div style="width:32px;height:32px;border-radius:8px;background:rgba(59,130,246,.1);border:1px solid rgba(59,130,246,.2);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
 
403
  </div>
404
  </div>
405
 
 
406
  <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
407
 
 
408
  <div style="display:flex;flex-direction:column;gap:16px;">
 
 
409
  <div class="card" style="padding:20px;">
410
  <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
411
  <div>
 
435
  <span style="padding:2px 8px;border-radius:4px;font-size:10px;font-weight:500;color:var(--text3);background:var(--border);">TIFF</span>
436
  </div>
437
  </div>
 
 
438
  <div id="file-preview" style="margin-top:12px;display:none;">
439
  <img id="img-preview" style="width:100%;max-height:200px;object-fit:contain;border-radius:8px;border:1px solid var(--border);"/>
440
  </div>
 
 
441
  <div id="file-list" style="margin-top:10px;display:flex;flex-direction:column;gap:8px;"></div>
442
  </div>
443
 
 
444
  <div class="card" style="padding:16px;">
445
  <button id="exec-btn" class="btn-primary" style="width:100%;padding:14px;display:flex;align-items:center;justify-content:center;gap:10px;" disabled onclick="executeExtraction()">
446
  <span id="btn-idle" style="display:flex;align-items:center;gap:8px;">
 
452
  Processing…
453
  </span>
454
  </button>
 
 
455
  <div id="prog-wrapper" style="display:none;margin-top:14px;">
456
  <div style="display:flex;justify-content:space-between;margin-bottom:6px;">
457
+ <span id="prog-label" style="font-size:12px;color:var(--text2);">Initializing...</span>
458
+ <span id="prog-pct" style="font-size:12px;font-weight:600;color:var(--blue-light);">0%</span>
 
 
 
 
 
 
 
 
 
459
  </div>
460
+ <div class="prog-track">
461
+ <div id="prog-fill" class="prog-fill" style="width:0%;"></div>
 
462
  </div>
463
+ <div style="display:grid;grid-template-columns:repeat(4,1fr);margin-top:12px;text-align:center;gap:4px;">
464
+ <div>
465
+ <div id="stage-1" class="stage-dot" style="margin:0 auto 6px;"></div>
466
+ <p style="font-size:10px;color:var(--text4);">Ingestion</p>
467
+ </div>
468
+ <div>
469
+ <div id="stage-2" class="stage-dot" style="margin:0 auto 6px;"></div>
470
+ <p style="font-size:10px;color:var(--text4);">Model Parse</p>
471
+ </div>
472
+ <div>
473
+ <div id="stage-3" class="stage-dot" style="margin:0 auto 6px;"></div>
474
+ <p style="font-size:10px;color:var(--text4);">Validation</p>
475
+ </div>
476
+ <div>
477
+ <div id="stage-4" class="stage-dot" style="margin:0 auto 6px;"></div>
478
+ <p style="font-size:10px;color:var(--text4);">Export</p>
479
+ </div>
480
  </div>
481
  </div>
482
  </div>
483
+ </div>
484
 
485
+ <div style="display:flex;flex-direction:column;gap:16px;">
486
+ <div class="card" style="padding:16px;display:flex;flex-direction:column;height:100%;min-height:480px;">
487
+ <div style="display:flex;align-items:center;justify-content:between;border-bottom:1px solid var(--border);padding-bottom:12px;margin-bottom:12px;">
488
+ <div style="display:flex;gap:6px;background:var(--surface);padding:4px;border-radius:8px;border:1px solid var(--border);">
489
+ <button id="tab-data" class="tab-btn active" onclick="switchTab('data')">Extracted Data</button>
490
+ <button id="tab-chat" class="tab-btn" onclick="switchTab('chat')">AI Chat Agent</button>
491
  </div>
492
+ <span class="section-label">Stage 02</span>
493
  </div>
494
 
495
+ <div id="view-data" style="display:flex;flex-direction:column;gap:12px;flex-grow:1;">
496
+ <div id="data-placeholder" style="display:flex;flex-direction:column;align-items:center;justify-content:center;flex-grow:1;color:var(--text4);text-align:center;padding:4px;">
497
+ <svg width="32" height="32" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5" style="margin-bottom:8px;"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 0 1-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 0 1 1.5.124m7.5 10.376A8.965 8.965 0 0 0 12 12.75c-.131 0-.262.007-.392.021m3.416 4.479a8.978 8.978 0 0 4-4.479m-4 4.479a9.15 9.15 0 0 1-3.084-2.435m0 0A8.958 8.958 0 0 1 12 12.75c1.24 0 2.391.251 3.434.703m-6.434-.703a9.036 9.036 0 0 1 1.566-3.472m0 0a9.043 9.043 0 0 1 3.468-1.564"/></svg>
498
+ <p style="font-size:13px;font-weight:500;">Awaiting Extraction Results</p>
499
+ <p style="font-size:11px;margin-top:2px;">Execute extraction to inspect payload schemas.</p>
500
  </div>
 
 
501
 
502
+ <div id="data-display" style="display:none;flex-direction:column;gap:12px;flex-grow:1;">
503
+ <div class="code-view" style="flex-grow:1;padding:14px;overflow-y:auto;max-height:320px;">
504
+ <pre class="json-pre"><code id="json-code"></code></pre>
505
+ </div>
506
+
507
+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
508
+ <div class="dl-card" style="padding:12px;display:flex;align-items:center;justify-content:between;cursor:pointer;" onclick="downloadCSV()">
509
+ <div>
510
+ <p style="font-size:12px;font-weight:600;color:var(--text);">Structured CSV</p>
511
+ <p style="font-size:10px;color:var(--text4);margin-top:1px;">Tabular matrix mapping</p>
512
+ </div>
513
+ <svg width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="var(--blue-light)" stroke-width="2"><path d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
514
  </div>
515
+ <div class="dl-card" style="padding:12px;display:flex;align-items:center;justify-content:between;cursor:pointer;" onclick="downloadJSON()">
516
+ <div>
517
+ <p style="font-size:12px;font-weight:600;color:var(--text);">Raw Payload JSON</p>
518
+ <p style="font-size:10px;color:var(--text4);margin-top:1px;">Standard REST response</p>
519
+ </div>
520
+ <svg width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="var(--purple)" stroke-width="2"><path d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
521
  </div>
522
  </div>
 
 
 
 
523
  </div>
524
  </div>
 
525
 
526
+ <div id="view-chat" style="display:none;flex-direction:column;height:100%;flex-grow:1;">
527
+ <div id="chat-messages" style="flex-grow:1;overflow-y:auto;max-height:300px;display:flex;flex-direction:column;gap:12px;padding-right:4px;margin-bottom:12px;">
528
+ <div class="fade-up" style="display:flex;gap:10px;align-items:start;">
529
+ <div class="ai-avatar" style="width:26px;height:26px;border-radius:50%;background:var(--blue);display:flex;align-items:center;justify-content:center;color:#fff;font-size:10px;font-weight:700;flex-shrink:0;margin-top:2px;">AI</div>
530
+ <div class="bubble-ai" style="padding:10px 14px;font-size:13px;line-height:1.5;color:var(--text);">
531
+ Hello! I am your document agent. Once you extract a document, ask me questions like <em>"What is the total amount?"</em> or <em>"Who is the vendor?"</em>.
532
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
533
  </div>
534
  </div>
 
535
 
536
+ <div style="display:flex;gap:8px;position:relative;">
537
+ <textarea id="chat-textarea" class="chat-input" placeholder="Query document contents..." rows="1" onkeydown="handleChatKey(event)"></textarea>
538
+ <button id="chat-send-btn" style="position:absolute;right:8px;top:8px;color:var(--text3);cursor:pointer;transition:color .15s;" onclick="sendChatMessage()">
539
+ <svg width="20" height="20" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5"/></svg>
 
 
 
 
540
  </button>
541
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542
  </div>
543
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
544
  </div>
 
545
 
546
+ </div>
547
  </main>
548
 
 
549
  <script>
550
+ let currentBase64 = "";
551
+ let latestJSONPayload = null;
552
+ let parsedCount = 0;
553
+
554
+ function showToast(message, type = "success") {
555
+ const container = document.getElementById("toast-root");
556
+ const toast = document.createElement("div");
557
+ toast.className = "toast card";
558
+ toast.style.cssText = `padding:12px 16px;display:flex;align-items:center;gap:10px;min-width:260px;background:var(--surface2);border-left:4px solid ${type === 'success' ? 'var(--green)' : 'var(--red)'};`;
559
+ toast.innerHTML = `
560
+ <span style="font-size:13px;font-weight:500;color:var(--text);flex-grow:1;">${message}</span>
561
+ <button onclick="this.parentElement.remove()" style="color:var(--text4);font-size:12px;cursor:pointer;">✕</button>
562
+ `;
563
+ container.appendChild(toast);
564
+ setTimeout(() => {
565
+ toast.classList.add("hide");
566
+ setTimeout(() => toast.remove(), 300);
567
+ }, 4000);
568
  }
569
 
570
+ function handleDrop(e) {
571
+ e.preventDefault();
572
+ document.getElementById("drop-zone").classList.remove("drag-over");
573
+ if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
574
+ handleFiles(e.dataTransfer.files);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
575
  }
 
 
576
  }
577
 
578
+ function handleFiles(files) {
579
+ if (files.length === 0) return;
580
+ const file = files[0];
581
+
582
+ const fileList = document.getElementById("file-list");
583
+ fileList.innerHTML = `
584
+ <div class="file-item" style="padding:10px 14px;display:flex;align-items:center;justify-content:between;">
585
+ <div style="display:flex;align-items:center;gap:10px;overflow:hidden;">
586
+ <svg width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="var(--text3)" stroke-width="2"><path d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
587
+ <span style="font-size:12px;font-weight:500;color:var(--text2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${file.name}</span>
 
 
 
 
588
  </div>
589
+ <span style="font-size:11px;color:var(--text4);">${(file.size / 1024).toFixed(1)} KB</span>
590
+ </div>
591
+ `;
592
+
593
+ const reader = new FileReader();
594
+ reader.onload = function(e) {
595
+ currentBase64 = e.target.result;
596
+
597
+ const hiddenInput = document.querySelector("#gr-image-input textarea");
598
+ if(hiddenInput) {
599
+ hiddenInput.value = currentBase64;
600
+ hiddenInput.dispatchEvent(new Event('input', { bubbles: true }));
601
+ }
602
+
603
+ if (file.type.startsWith("image/")) {
604
+ document.getElementById("img-preview").src = currentBase64;
605
+ document.getElementById("file-preview").style.display = "block";
606
+ } else {
607
+ document.getElementById("file-preview").style.display = "none";
608
+ }
609
+
610
+ document.getElementById("exec-btn").removeAttribute("disabled");
611
+ showToast("Document staged for extraction.");
612
+ };
613
+ reader.readAsDataURL(file);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
614
  }
615
 
616
+ function executeExtraction() {
617
+ if (!currentBase64) return;
618
+
619
+ document.getElementById("exec-btn").setAttribute("disabled", "true");
620
+ document.getElementById("btn-idle").style.display = "none";
621
+ document.getElementById("btn-loading").style.display = "flex";
622
+ document.getElementById("prog-wrapper").style.display = "block";
623
+
624
+ document.getElementById("status-dot").style.background = "var(--amber)";
625
+ document.getElementById("status-dot").style.boxShadow = "0 0 8px var(--amber)";
626
+ document.getElementById("status-text").innerText = "Analyzing Schema...";
627
+
628
+ for(let i=1; i<=4; i++) {
629
+ document.getElementById(`stage-${i}`).className = "stage-dot";
630
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
631
 
632
+ animateProgress(0, 25, "Ingesting Document...", 1, () => {
633
+ animateProgress(25, 65, "Running Vision Transformer Model...", 2, () => {
634
+ const grBtn = document.getElementById("gr-parse-btn");
635
+ if(grBtn) grBtn.click();
636
+ waitForExtractionResponse();
637
+ });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
638
  });
639
  }
640
 
641
+ function animateProgress(start, end, label, currentStage, callback) {
642
+ document.getElementById("prog-label").innerText = label;
643
+ document.getElementById(`stage-${currentStage}`).className = "stage-dot active";
644
+
645
+ let current = start;
646
+ let interval = setInterval(() => {
647
+ current += 2;
648
+ if(current >= end) {
649
+ current = end;
650
+ clearInterval(interval);
651
+ document.getElementById(`stage-${currentStage}`).className = "stage-dot done";
652
+ if(callback) callback();
653
  }
654
+ document.getElementById("prog-pct").innerText = `${current}%`;
655
+ document.getElementById("prog-fill").style.width = `${current}%`;
656
+ }, 40);
657
+ }
658
 
659
+ function waitForExtractionResponse() {
660
+ const hiddenOut = document.querySelector("#gr-json-output textarea");
661
+ let checks = 0;
662
+
663
+ let checker = setInterval(() => {
664
+ checks++;
665
+ if (hiddenOut && hiddenOut.value && hiddenOut.value.trim() !== "") {
666
+ clearInterval(checker);
667
+ try {
668
+ const payload = JSON.parse(hiddenOut.value);
669
+ handleExtractionSuccess(payload);
670
+ } catch (err) {
671
+ handleExtractionError("Invalid system payload received.");
672
+ }
673
+ } else if (checks > 350) {
674
+ clearInterval(checker);
675
+ handleExtractionError("Model connection timeout.");
 
 
 
 
 
 
676
  }
677
+ }, 100);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
678
  }
679
 
680
+ function handleExtractionSuccess(payload) {
681
+ latestJSONPayload = payload;
682
+ parsedCount++;
683
+
684
+ animateProgress(65, 90, "Cross-Field Validation...", 3, () => {
685
+ animateProgress(90, 100, "Compiling Result Schemes...", 4, () => {
686
+ document.getElementById("btn-idle").style.display = "flex";
687
+ document.getElementById("btn-loading").style.display = "none";
688
+
689
+ document.getElementById("status-dot").style.background = "#34d399";
690
+ document.getElementById("status-dot").style.boxShadow = "0 0 6px #34d399";
691
+ document.getElementById("status-text").innerText = "System Idle";
692
+
693
+ document.getElementById("st-docs").innerText = parsedCount;
694
+ document.getElementById("st-fields").innerText = Object.keys(payload.extracted_data || {}).length;
695
+ document.getElementById("st-time").innerText = `${payload.parse_time_seconds || '0.45'}s`;
696
+ document.getElementById("st-conf").innerText = `${((payload.security_and_compliance || {}).confidence_score * 100 || 97).toFixed(0)}%`;
697
+
698
+ const jsonStr = JSON.stringify(payload, null, 2);
699
+ document.getElementById("json-code").innerHTML = syntaxHighlightJSON(jsonStr);
700
+
701
+ document.getElementById("data-placeholder").style.display = "none";
702
+ document.getElementById("data-display").style.display = "flex";
703
+
704
+ switchTab('data');
705
+ showToast("Document successfully processed!");
706
+
707
+ const hiddenOut = document.querySelector("#gr-json-output textarea");
708
+ if(hiddenOut) {
709
+ hiddenOut.value = "";
710
+ hiddenOut.dispatchEvent(new Event('input', { bubbles: true }));
711
+ }
712
+ });
713
+ });
714
  }
715
 
716
+ function handleExtractionError(errLog) {
717
+ document.getElementById("btn-idle").style.display = "flex";
718
+ document.getElementById("btn-loading").style.display = "none";
719
+ document.getElementById("prog-wrapper").style.display = "none";
720
+
721
+ document.getElementById("status-dot").style.background = "var(--red)";
722
+ document.getElementById("status-dot").style.boxShadow = "0 0 8px var(--red)";
723
+ document.getElementById("status-text").innerText = "Error Detected";
724
+
725
+ showToast(errLog, "error");
726
  }
727
 
728
+ function syntaxHighlightJSON(json) {
729
+ json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
730
+ return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g, function (match) {
731
+ let cls = 'json-number';
732
+ if (/^"/.test(match)) {
733
+ if (/:$/.test(match)) {
734
+ cls = 'json-key';
735
+ return `<span class="${cls}">${match.replace(':', '')}</span>:`;
736
+ } else {
737
+ cls = 'json-string';
738
+ }
739
+ } else if (/true|false/.test(match)) {
740
+ cls = 'json-bool';
741
+ } else if (/null/.test(match)) {
742
+ cls = 'json-null';
743
+ }
744
+ return `<span class="${cls}">${match}</span>`;
745
+ });
746
  }
747
 
748
+ function switchTab(tab) {
749
+ if(tab === 'data') {
750
+ document.getElementById("tab-data").classList.add("active");
751
+ document.getElementById("tab-chat").classList.remove("active");
752
+ document.getElementById("view-data").style.display = "flex";
753
+ document.getElementById("view-chat").style.display = "none";
754
+ } else {
755
+ document.getElementById("tab-data").classList.remove("active");
756
+ document.getElementById("tab-chat").classList.add("active");
757
+ document.getElementById("view-data").style.display = "none";
758
+ document.getElementById("view-chat").style.display = "flex";
 
 
 
 
 
 
759
  }
760
  }
761
 
762
+ function handleChatKey(e) {
763
+ if(e.key === 'Enter' && !e.shiftKey) {
764
+ e.preventDefault();
765
+ sendChatMessage();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
766
  }
 
 
767
  }
768
 
769
+ function sendChatMessage() {
770
+ const txtArea = document.getElementById("chat-textarea");
771
+ const msg = txtArea.value.trim();
772
+ if(!msg) return;
773
+
774
+ txtArea.value = "";
775
+
776
+ const chatContainer = document.getElementById("chat-messages");
777
+ const userDiv = document.createElement("div");
778
+ userDiv.className = "fade-up";
779
+ userDiv.style = "display:flex;gap:10px;align-items:start;justify-content:flex-end;";
780
+ userDiv.innerHTML = `
781
+ <div class="bubble-user" style="padding:10px 14px;font-size:13px;line-height:1.5;color:var(--text);max-width:85%;">
782
+ ${msg}
783
  </div>
784
+ `;
785
+ chatContainer.appendChild(userDiv);
786
+ chatContainer.scrollTop = chatContainer.scrollHeight;
787
+
788
+ const thinkDiv = document.createElement("div");
789
+ thinkDiv.id = "ai-thinking-placeholder";
790
+ thinkDiv.className = "fade-up";
791
+ thinkDiv.style = "display:flex;gap:10px;align-items:start;";
792
+ thinkDiv.innerHTML = `
793
+ <div class="ai-avatar" style="width:26px;height:26px;border-radius:50%;background:var(--blue);display:flex;align-items:center;justify-content:center;color:#fff;font-size:10px;font-weight:700;flex-shrink:0;margin-top:2px;">AI</div>
794
+ <div class="bubble-ai" style="padding:10px 14px;display:flex;align-items:center;gap:4px;height:36px;">
795
+ <span class="typing-dot" style="width:5px;height:5px;border-radius:50%;background:var(--text2);"></span>
796
+ <span class="typing-dot" style="width:5px;height:5px;border-radius:50%;background:var(--text2);"></span>
797
+ <span class="typing-dot" style="width:5px;height:5px;border-radius:50%;background:var(--text2);"></span>
798
+ </div>
799
+ `;
800
+ chatContainer.appendChild(thinkDiv);
801
+ chatContainer.scrollTop = chatContainer.scrollHeight;
802
+
803
+ const grMsgInput = document.querySelector("#gr-chat-msg textarea");
804
+ const grJsonInput = document.querySelector("#gr-chat-json textarea");
805
+ const grChatBtn = document.getElementById("gr-chat-btn");
806
+
807
+ if (grMsgInput && grChatBtn) {
808
+ grMsgInput.value = msg;
809
+ grMsgInput.dispatchEvent(new Event('input', { bubbles: true }));
810
+
811
+ grJsonInput.value = latestJSONPayload ? JSON.stringify(latestJSONPayload) : "";
812
+ grJsonInput.dispatchEvent(new Event('input', { bubbles: true }));
813
+
814
+ grChatBtn.click();
815
+ waitForChatResponse();
 
 
 
 
 
816
  }
817
  }
818
 
819
+ function waitForChatResponse() {
820
+ const hiddenChatOut = document.querySelector("#gr-chat-out textarea");
821
+ let checks = 0;
822
+
823
+ let checker = setInterval(() => {
824
+ checks++;
825
+ if (hiddenChatOut && hiddenChatOut.value && hiddenChatOut.value.trim() !== "") {
826
+ clearInterval(checker);
827
+ const reply = hiddenChatOut.value;
828
+
829
+ const placeholder = document.getElementById("ai-thinking-placeholder");
830
+ if(placeholder) placeholder.remove();
831
+
832
+ const chatContainer = document.getElementById("chat-messages");
833
+ const aiDiv = document.createElement("div");
834
+ aiDiv.className = "fade-up";
835
+ aiDiv.style = "display:flex;gap:10px;align-items:start;";
836
+
837
+ let formattedReply = reply.replace(/\n/g, '<br/>').replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>').replace(/•/g, '&bull;');
838
+
839
+ aiDiv.innerHTML = `
840
+ <div class="ai-avatar" style="width:26px;height:26px;border-radius:50%;background:var(--blue);display:flex;align-items:center;justify-content:center;color:#fff;font-size:10px;font-weight:700;flex-shrink:0;margin-top:2px;">AI</div>
841
+ <div class="bubble-ai" style="padding:10px 14px;font-size:13px;line-height:1.5;color:var(--text);max-width:85%;">
842
+ ${formattedReply}
843
+ </div>
844
+ `;
845
+ chatContainer.appendChild(aiDiv);
846
+ chatContainer.scrollTop = chatContainer.scrollHeight;
847
+
848
+ hiddenChatOut.value = "";
849
+ hiddenChatOut.dispatchEvent(new Event('input', { bubbles: true }));
850
+
851
+ } else if (checks > 150) {
852
+ clearInterval(checker);
853
+ const placeholder = document.getElementById("ai-thinking-placeholder");
854
+ if(placeholder) placeholder.remove();
855
+ showToast("Agent response timed out.", "error");
856
+ }
857
+ }, 100);
858
  }
859
 
860
+ function downloadCSV() {
861
+ if(!latestJSONPayload || !latestJSONPayload._csv_b64) return;
862
+ const link = document.createElement("a");
863
+ link.href = "data:text/csv;base64," + latestJSONPayload._csv_b64;
864
+ link.download = "omniparse_structured_result.csv";
865
+ link.click();
 
 
866
  }
867
 
868
+ function downloadJSON() {
869
+ if(!latestJSONPayload) return;
870
+ const jsonData = JSON.stringify(latestJSONPayload, null, 2);
871
+ const blob = new Blob([jsonData], { type: "application/json" });
872
+ const link = document.createElement("a");
873
+ link.href = URL.createObjectURL(blob);
874
+ link.download = "omniparse_raw_payload.json";
875
+ link.click();
 
 
 
 
 
 
 
876
  }
877
  </script>
878
+ </body>
879
  </html>
880
  """
881
 
882
+ # ─── Gradio Block Core Setup ────────────────────────────────────────────────
883
+ with gr.Blocks(css=CUSTOM_CSS) as demo:
 
 
884
  gr.HTML(HTML_UI)
885
 
 
886
  with gr.Row(elem_id="hidden-controls", visible=False):
887
  with gr.Column():
888
  gr_image_input = gr.Textbox(
 
914
  visible=False,
915
  )
916
 
 
917
  gr_parse_btn.click(
918
  fn=gr_parse,
919
  inputs=[gr_image_input],
 
927
  )
928
 
929
  if __name__ == "__main__":
930
+ demo.launch()