prithivMLmods commited on
Commit
fb309bc
·
verified ·
1 Parent(s): 198afe4

update app

Browse files
Files changed (1) hide show
  1. app.py +869 -1286
app.py CHANGED
@@ -1,7 +1,12 @@
1
  import os
2
- import random
3
- import uuid
 
4
  import json
 
 
 
 
5
  from threading import Thread
6
 
7
  import gradio as gr
@@ -12,862 +17,78 @@ from PIL import Image, ImageOps
12
  from transformers import (
13
  Qwen2_5_VLForConditionalGeneration,
14
  Qwen3VLForConditionalGeneration,
15
- AutoModelForVision2Seq,
16
  AutoProcessor,
 
17
  TextIteratorStreamer,
18
  )
19
 
20
  from docling_core.types.doc import DoclingDocument, DocTagsDocument
21
 
22
- import re
23
- import ast
24
- import html
25
 
26
  MAX_MAX_NEW_TOKENS = 4096
27
  DEFAULT_MAX_NEW_TOKENS = 2048
28
  MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
29
 
30
  device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
 
31
 
 
32
  print("torch.__version__ =", torch.__version__)
33
  print("Using device:", device)
34
 
35
- css = r"""
36
- @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&family=IBM+Plex+Mono:wght@400;500;600&display=swap');
37
-
38
- *{box-sizing:border-box;margin:0;padding:0}
39
- body,.gradio-container{
40
- background:#0b0d05!important;
41
- font-family:'Outfit',system-ui,-apple-system,sans-serif!important;
42
- color:#eef7d1!important;
43
- min-height:100vh;
44
- }
45
- footer{display:none!important}
46
-
47
- .hidden-input{
48
- display:none!important;
49
- height:0!important;
50
- overflow:hidden!important;
51
- margin:0!important;
52
- padding:0!important;
53
- }
54
-
55
- #gradio-run-btn,
56
- #example-load-btn{
57
- position:absolute!important;
58
- left:-9999px!important;
59
- top:-9999px!important;
60
- width:1px!important;
61
- height:1px!important;
62
- opacity:0.01!important;
63
- pointer-events:none!important;
64
- overflow:hidden!important;
65
- }
66
-
67
- .app-shell{
68
- background:#111507;
69
- border:1px solid rgba(211,245,39,.18);
70
- border-radius:18px;
71
- margin:14px auto;
72
- max-width:1450px;
73
- overflow:hidden;
74
- box-shadow:0 24px 60px rgba(0,0,0,.45), 0 0 0 1px rgba(211,245,39,.04);
75
- }
76
-
77
- .app-header{
78
- background:linear-gradient(135deg,#151a09,#1c220d);
79
- border-bottom:1px solid rgba(211,245,39,.14);
80
- padding:16px 24px;
81
- display:flex;
82
- align-items:center;
83
- justify-content:space-between;
84
- flex-wrap:wrap;
85
- gap:12px;
86
- }
87
- .app-header-left{
88
- display:flex;
89
- align-items:center;
90
- gap:14px;
91
- }
92
- .app-logo{
93
- width:42px;
94
- height:42px;
95
- border-radius:12px;
96
- display:flex;
97
- align-items:center;
98
- justify-content:center;
99
- background:linear-gradient(135deg,#D3F527,#b5d71e);
100
- box-shadow:0 8px 22px rgba(211,245,39,.28);
101
- }
102
- .app-logo svg{
103
- width:24px;
104
- height:24px;
105
- fill:#111507;
106
- }
107
- .app-title{
108
- font-size:20px;
109
- font-weight:800;
110
- color:#f6ffd8!important;
111
- letter-spacing:-.3px;
112
- }
113
- .app-badge{
114
- font-size:11px;
115
- font-weight:700;
116
- padding:4px 10px;
117
- border-radius:999px;
118
- background:rgba(211,245,39,.12);
119
- color:#D3F527;
120
- border:1px solid rgba(211,245,39,.22);
121
- letter-spacing:.3px;
122
- }
123
-
124
- .app-main{
125
- display:flex;
126
- gap:0;
127
- min-height:780px;
128
- }
129
- .app-left{
130
- flex:1.05;
131
- min-width:0;
132
- border-right:1px solid rgba(211,245,39,.12);
133
- display:flex;
134
- flex-direction:column;
135
- background:#111507;
136
- }
137
- .app-right{
138
- width:470px;
139
- flex-shrink:0;
140
- display:flex;
141
- flex-direction:column;
142
- background:#131808;
143
- }
144
-
145
- .panel{
146
- border-bottom:1px solid rgba(211,245,39,.12);
147
- }
148
- .panel-title{
149
- padding:13px 18px;
150
- font-size:12px;
151
- font-weight:700;
152
- color:#a6ba57;
153
- text-transform:uppercase;
154
- letter-spacing:.9px;
155
- border-bottom:1px solid rgba(211,245,39,.08);
156
- }
157
- .panel-body{
158
- padding:16px 18px;
159
- display:flex;
160
- flex-direction:column;
161
- gap:10px;
162
- }
163
-
164
- .modern-label{
165
- font-size:13px;
166
- font-weight:600;
167
- color:#d7e7a0;
168
- margin-bottom:4px;
169
- }
170
- .modern-input,.modern-textarea{
171
- width:100%;
172
- background:#0d1006;
173
- border:1px solid rgba(211,245,39,.14);
174
- border-radius:10px;
175
- color:#f1f7dc;
176
- outline:none;
177
- font-family:'Outfit',sans-serif;
178
- transition:border-color .2s, box-shadow .2s;
179
- }
180
- .modern-input{
181
- height:44px;
182
- padding:0 14px;
183
- font-size:14px;
184
- }
185
- .modern-textarea{
186
- min-height:90px;
187
- padding:12px 14px;
188
- font-size:14px;
189
- resize:vertical;
190
- }
191
- .modern-input:focus,.modern-textarea:focus{
192
- border-color:#D3F527;
193
- box-shadow:0 0 0 3px rgba(211,245,39,.16);
194
- }
195
- .modern-input::placeholder,.modern-textarea::placeholder{
196
- color:#6c7650;
197
- }
198
- .modern-input.error-flash,.modern-textarea.error-flash{
199
- border-color:#ef4444!important;
200
- box-shadow:0 0 0 3px rgba(239,68,68,.18)!important;
201
- animation:shake .35s ease;
202
- }
203
- @keyframes shake{
204
- 0%,100%{transform:translateX(0)}
205
- 20%,60%{transform:translateX(-4px)}
206
- 40%,80%{transform:translateX(4px)}
207
- }
208
-
209
- .upload-zone{
210
- position:relative;
211
- min-height:360px;
212
- background:#0a0d04;
213
- border:2px dashed rgba(211,245,39,.18);
214
- border-radius:16px;
215
- margin:18px;
216
- overflow:hidden;
217
- transition:all .2s ease;
218
- }
219
- .upload-zone.drag-over{
220
- border-color:#D3F527;
221
- background:rgba(211,245,39,.05);
222
- box-shadow:inset 0 0 0 1px rgba(211,245,39,.18);
223
- }
224
- .upload-empty{
225
- position:absolute;
226
- inset:0;
227
- display:flex;
228
- align-items:center;
229
- justify-content:center;
230
- padding:28px;
231
- }
232
- .upload-click-area{
233
- display:flex;
234
- flex-direction:column;
235
- align-items:center;
236
- justify-content:center;
237
- gap:8px;
238
- text-align:center;
239
- padding:30px 40px;
240
- border-radius:16px;
241
- cursor:pointer;
242
- background:rgba(211,245,39,.03);
243
- transition:all .2s ease;
244
- }
245
- .upload-click-area:hover{
246
- background:rgba(211,245,39,.08);
247
- transform:translateY(-1px);
248
- }
249
- .upload-click-area svg{
250
- width:86px;
251
- height:86px;
252
- }
253
- .upload-main-text{
254
- color:#e9f7bd;
255
- font-size:15px;
256
- font-weight:700;
257
- }
258
- .upload-sub-text{
259
- color:#8e9a62;
260
- font-size:12px;
261
- max-width:400px;
262
- }
263
- .preview-wrap{
264
- width:100%;
265
- height:100%;
266
- display:none;
267
- align-items:center;
268
- justify-content:center;
269
- padding:14px;
270
- }
271
- .preview-wrap.visible{display:flex}
272
- .preview-wrap img{
273
- max-width:100%;
274
- max-height:330px;
275
- object-fit:contain;
276
- border-radius:12px;
277
- border:1px solid rgba(211,245,39,.12);
278
- background:#0d1006;
279
- }
280
- .preview-actions{
281
- display:none;
282
- gap:8px;
283
- padding:0 18px 18px;
284
- }
285
- .preview-actions.visible{display:flex}
286
-
287
- .modern-btn{
288
- display:inline-flex;
289
- align-items:center;
290
- justify-content:center;
291
- gap:8px;
292
- height:40px;
293
- padding:0 16px;
294
- border-radius:10px;
295
- border:1px solid rgba(211,245,39,.14);
296
- background:#171d0a;
297
- color:#eef7d1!important;
298
- cursor:pointer;
299
- font-family:'Outfit',sans-serif;
300
- font-size:13px;
301
- font-weight:700;
302
- transition:all .18s ease;
303
- }
304
- .modern-btn:hover{
305
- border-color:#D3F527;
306
- color:#111507!important;
307
- background:#D3F527;
308
- }
309
- .modern-btn.primary{
310
- width:100%;
311
- height:46px;
312
- font-size:15px;
313
- background:linear-gradient(135deg,#D3F527,#b7d91e);
314
- color:#111507!important;
315
- border:none;
316
- box-shadow:0 10px 26px rgba(211,245,39,.22), inset 0 1px 0 rgba(255,255,255,.18);
317
- }
318
- .modern-btn.primary:hover{
319
- transform:translateY(-1px);
320
- box-shadow:0 14px 32px rgba(211,245,39,.28), inset 0 1px 0 rgba(255,255,255,.24);
321
- }
322
- .modern-btn svg{
323
- width:16px;
324
- height:16px;
325
- fill:currentColor;
326
- }
327
-
328
- .examples-section{
329
- border-top:1px solid rgba(211,245,39,.10);
330
- padding:14px 18px 18px;
331
- }
332
- .examples-title{
333
- font-size:12px;
334
- font-weight:700;
335
- color:#9caf57;
336
- text-transform:uppercase;
337
- letter-spacing:.8px;
338
- margin-bottom:10px;
339
- }
340
- .examples-scroll{
341
- display:flex;
342
- gap:10px;
343
- overflow-x:auto;
344
- padding-bottom:8px;
345
- }
346
- .examples-scroll::-webkit-scrollbar{height:6px}
347
- .examples-scroll::-webkit-scrollbar-thumb{background:#313a14;border-radius:8px}
348
- .example-card{
349
- flex-shrink:0;
350
- width:210px;
351
- background:#0d1006;
352
- border:1px solid rgba(211,245,39,.12);
353
- border-radius:12px;
354
- overflow:hidden;
355
- cursor:pointer;
356
- transition:all .18s ease;
357
- }
358
- .example-card:hover{
359
- border-color:#D3F527;
360
- transform:translateY(-2px);
361
- box-shadow:0 8px 20px rgba(211,245,39,.10);
362
- }
363
- .example-card.loading{
364
- opacity:.55;
365
- pointer-events:none;
366
- }
367
- .example-thumb{
368
- width:100%;
369
- height:110px;
370
- object-fit:cover;
371
- display:block;
372
- background:#151a09;
373
- }
374
- .example-meta{
375
- padding:10px 10px 8px;
376
- display:flex;
377
- align-items:center;
378
- justify-content:space-between;
379
- gap:8px;
380
- }
381
- .example-badge{
382
- display:inline-flex;
383
- padding:3px 8px;
384
- border-radius:999px;
385
- background:rgba(211,245,39,.10);
386
- color:#D3F527;
387
- font-size:10px;
388
- font-weight:700;
389
- font-family:'IBM Plex Mono',monospace;
390
- }
391
- .example-prompt{
392
- padding:0 10px 12px;
393
- color:#c9d7a0;
394
- font-size:12px;
395
- line-height:1.4;
396
- display:-webkit-box;
397
- -webkit-line-clamp:2;
398
- -webkit-box-orient:vertical;
399
- overflow:hidden;
400
- }
401
-
402
- .model-grid{
403
- display:grid;
404
- grid-template-columns:repeat(2,minmax(0,1fr));
405
- gap:8px;
406
- }
407
- .model-option{
408
- display:flex;
409
- align-items:center;
410
- justify-content:center;
411
- text-align:center;
412
- min-height:44px;
413
- padding:10px 12px;
414
- border-radius:10px;
415
- border:1px solid rgba(211,245,39,.12);
416
- background:#0d1006;
417
- color:#dce8b4;
418
- font-size:13px;
419
- font-weight:700;
420
- cursor:pointer;
421
- transition:all .18s ease;
422
- }
423
- .model-option:hover{
424
- border-color:#D3F527;
425
- }
426
- .model-option.active{
427
- background:#D3F527;
428
- border-color:#D3F527;
429
- color:#111507;
430
- }
431
-
432
- .output-frame{
433
- display:flex;
434
- flex-direction:column;
435
- min-height:0;
436
- flex:1;
437
- border-bottom:1px solid rgba(211,245,39,.12);
438
- }
439
- .output-header{
440
- padding:12px 18px;
441
- border-bottom:1px solid rgba(211,245,39,.08);
442
- display:flex;
443
- align-items:center;
444
- justify-content:space-between;
445
- }
446
- .output-title{
447
- font-size:13px;
448
- font-weight:800;
449
- text-transform:uppercase;
450
- letter-spacing:.8px;
451
- color:#f3ffd0;
452
- }
453
- .out-download-btn{
454
- display:none;
455
- align-items:center;
456
- justify-content:center;
457
- gap:6px;
458
- padding:4px 10px;
459
- border-radius:8px;
460
- border:1px solid rgba(211,245,39,.16);
461
- background:rgba(211,245,39,.06);
462
- color:#D3F527;
463
- font-size:11px;
464
- font-weight:700;
465
- cursor:pointer;
466
- }
467
- .out-download-btn.visible{display:inline-flex}
468
- .out-download-btn:hover{
469
- background:#D3F527;
470
- color:#111507;
471
- }
472
-
473
- .output-body{
474
- position:relative;
475
- padding:16px 18px 18px;
476
- display:flex;
477
- flex-direction:column;
478
- gap:12px;
479
- min-height:0;
480
- flex:1;
481
- }
482
- .output-label{
483
- font-size:12px;
484
- font-weight:700;
485
- color:#9caf57;
486
- text-transform:uppercase;
487
- letter-spacing:.8px;
488
- }
489
- .output-raw{
490
- width:100%;
491
- min-height:230px;
492
- max-height:230px;
493
- overflow-y:auto;
494
- overflow-x:hidden;
495
- resize:none;
496
- background:#0d1006;
497
- border:1px solid rgba(211,245,39,.14);
498
- border-radius:12px;
499
- color:#eef7d1;
500
- padding:12px 14px;
501
- font-size:13px;
502
- line-height:1.55;
503
- font-family:'IBM Plex Mono',monospace;
504
- white-space:pre-wrap;
505
- word-break:break-word;
506
- }
507
- .output-raw::-webkit-scrollbar,
508
- .formatted-output::-webkit-scrollbar{
509
- width:8px;
510
- height:8px;
511
- }
512
- .output-raw::-webkit-scrollbar-thumb,
513
- .formatted-output::-webkit-scrollbar-thumb{
514
- background:#313a14;
515
- border-radius:8px;
516
- }
517
- .formatted-output{
518
- width:100%;
519
- min-height:230px;
520
- max-height:230px;
521
- overflow:auto;
522
- background:#0d1006;
523
- border:1px solid rgba(211,245,39,.14);
524
- border-radius:12px;
525
- color:#eef7d1;
526
- padding:12px 14px;
527
- font-size:13px;
528
- line-height:1.6;
529
- white-space:pre-wrap;
530
- word-break:break-word;
531
- }
532
- .formatted-output code,.formatted-output pre{
533
- font-family:'IBM Plex Mono',monospace;
534
- }
535
-
536
- .loader{
537
- display:none;
538
- position:absolute;
539
- inset:0;
540
- background:rgba(11,13,5,.88);
541
- backdrop-filter:blur(4px);
542
- z-index:10;
543
- align-items:center;
544
- justify-content:center;
545
- flex-direction:column;
546
- gap:14px;
547
- }
548
- .loader.active{display:flex}
549
- .loader-spinner{
550
- width:36px;
551
- height:36px;
552
- border-radius:50%;
553
- border:3px solid rgba(211,245,39,.18);
554
- border-top-color:#D3F527;
555
- animation:spin .8s linear infinite;
556
- }
557
- @keyframes spin{to{transform:rotate(360deg)}}
558
- .loader-text{
559
- font-size:13px;
560
- font-weight:700;
561
- color:#d8eb96;
562
- }
563
 
564
- .settings-group{
565
- margin:16px 18px;
566
- border:1px solid rgba(211,245,39,.12);
567
- border-radius:14px;
568
- overflow:hidden;
569
- background:#101406;
570
- }
571
- .settings-group-title{
572
- padding:11px 14px;
573
- font-size:12px;
574
- font-weight:800;
575
- color:#a4b85e;
576
- text-transform:uppercase;
577
- letter-spacing:.8px;
578
- border-bottom:1px solid rgba(211,245,39,.08);
579
- }
580
- .settings-group-body{
581
- padding:14px;
582
- display:flex;
583
- flex-direction:column;
584
- gap:12px;
585
- }
586
- .slider-row{
587
- display:flex;
588
- align-items:center;
589
- gap:10px;
590
- }
591
- .slider-row label{
592
- min-width:118px;
593
- color:#dbe7b3;
594
- font-size:13px;
595
- font-weight:600;
596
- }
597
- .slider-row input[type="range"]{
598
- flex:1;
599
- height:6px;
600
- appearance:none;
601
- background:#29310f;
602
- border-radius:999px;
603
- outline:none;
604
- }
605
- .slider-row input[type="range"]::-webkit-slider-thumb{
606
- appearance:none;
607
- width:16px;
608
- height:16px;
609
- border-radius:50%;
610
- background:#D3F527;
611
- cursor:pointer;
612
- box-shadow:0 2px 8px rgba(211,245,39,.25);
613
- }
614
- .slider-row .slider-val{
615
- min-width:64px;
616
- text-align:right;
617
- font-size:12px;
618
- font-weight:700;
619
- color:#D3F527;
620
- font-family:'IBM Plex Mono',monospace;
621
- padding:4px 8px;
622
- border-radius:8px;
623
- background:#0c0f05;
624
- border:1px solid rgba(211,245,39,.12);
625
- }
626
- .gpu-group{
627
- border:1px solid rgba(211,245,39,.12);
628
- border-radius:12px;
629
- padding:12px;
630
- background:#0d1006;
631
- }
632
- .gpu-title{
633
- font-size:12px;
634
- font-weight:800;
635
- color:#e6f4b7;
636
- margin-bottom:8px;
637
- }
638
- .gpu-note{
639
- margin-top:8px;
640
- color:#8f9e5f;
641
- font-size:12px;
642
- line-height:1.45;
643
- }
644
- .ra-wrap{width:100%}
645
- .ra-inner{
646
- position:relative;
647
- display:flex;
648
- align-items:center;
649
- gap:0;
650
- padding:6px;
651
- background:#1c220d;
652
- border-radius:999px;
653
- overflow:hidden;
654
- width:100%;
655
- }
656
- .ra-input{display:none}
657
- .ra-label{
658
- position:relative;
659
- z-index:2;
660
- flex:1;
661
- text-align:center;
662
- padding:8px 6px;
663
- font-size:12px;
664
- font-weight:800;
665
- color:#9aaa66;
666
- cursor:pointer;
667
- transition:color .18s ease;
668
- user-select:none;
669
- white-space:nowrap;
670
- }
671
- .ra-highlight{
672
- position:absolute;
673
- z-index:1;
674
- top:6px;
675
- left:6px;
676
- height:calc(100% - 12px);
677
- border-radius:999px;
678
- background:#D3F527;
679
- box-shadow:0 2px 8px rgba(211,245,39,.22);
680
- transition:transform .2s ease, width .2s ease;
681
- }
682
- .ra-input:checked + .ra-label{
683
- color:#111507;
684
- }
685
 
686
- .toast-notification{
687
- position:fixed;
688
- top:24px;
689
- left:50%;
690
- transform:translateX(-50%) translateY(-120%);
691
- z-index:9999;
692
- padding:10px 20px;
693
- border-radius:10px;
694
- font-size:14px;
695
- font-weight:700;
696
- display:flex;
697
- align-items:center;
698
- gap:8px;
699
- box-shadow:0 10px 28px rgba(0,0,0,.35);
700
- transition:transform .35s ease, opacity .35s ease;
701
- opacity:0;
702
- pointer-events:none;
703
- }
704
- .toast-notification.visible{
705
- transform:translateX(-50%) translateY(0);
706
- opacity:1;
707
- pointer-events:auto;
708
- }
709
- .toast-notification.error{
710
- background:linear-gradient(135deg,#dc2626,#b91c1c);
711
- color:#fff;
712
- }
713
- .toast-notification.warning{
714
- background:linear-gradient(135deg,#d97706,#b45309);
715
- color:#fff;
716
- }
717
- .toast-notification.info{
718
- background:linear-gradient(135deg,#8cb000,#6f8d00);
719
- color:#101406;
720
- }
721
-
722
- .statusbar{
723
- height:36px;
724
- display:flex;
725
- align-items:center;
726
- gap:10px;
727
- padding:0 18px;
728
- border-top:1px solid rgba(211,245,39,.12);
729
- background:#121708;
730
- font-size:12px;
731
- color:#86955b;
732
- font-family:'IBM Plex Mono',monospace;
733
- }
734
- .status-chip{
735
- padding:4px 10px;
736
- border-radius:999px;
737
- background:rgba(211,245,39,.08);
738
- color:#D3F527;
739
- }
740
-
741
- .exp-note{
742
- padding:12px 18px;
743
- border-top:1px solid rgba(211,245,39,.10);
744
- color:#7f8b57;
745
- font-size:12px;
746
- text-align:center;
747
- }
748
- .exp-note a{
749
- color:#D3F527;
750
- text-decoration:none;
751
- }
752
- .exp-note a:hover{text-decoration:underline}
753
-
754
- .gpu-radio-mount{
755
- margin-top:6px;
756
- }
757
-
758
- @media(max-width:980px){
759
- .app-main{flex-direction:column}
760
- .app-left{border-right:none;border-bottom:1px solid rgba(211,245,39,.12)}
761
- .app-right{width:100%}
762
- .model-grid{grid-template-columns:repeat(2,minmax(0,1fr))}
763
- }
764
- @media(max-width:640px){
765
- .model-grid{grid-template-columns:1fr}
766
- }
767
- """
768
-
769
- class RadioAnimated(gr.HTML):
770
- def __init__(self, choices, value=None, **kwargs):
771
- if not choices or len(choices) < 2:
772
- raise ValueError("RadioAnimated requires at least 2 choices.")
773
- if value is None:
774
- value = choices[0]
775
-
776
- uid = uuid.uuid4().hex[:8]
777
- group_name = f"ra-{uid}"
778
-
779
- inputs_html = "\n".join(
780
- f"""
781
- <input class="ra-input" type="radio" name="{group_name}" id="{group_name}-{i}" value="{c}">
782
- <label class="ra-label" for="{group_name}-{i}">{c}</label>
783
- """
784
- for i, c in enumerate(choices)
785
- )
786
-
787
- html_template = f"""
788
- <div class="ra-wrap" data-ra="{uid}">
789
- <div class="ra-inner">
790
- <div class="ra-highlight"></div>
791
- {inputs_html}
792
- </div>
793
- </div>
794
- """
795
-
796
- js_on_load = r"""
797
- (() => {
798
- const highlight = element.querySelector('.ra-highlight');
799
- const inputs = Array.from(element.querySelectorAll('.ra-input'));
800
- if (!inputs.length) return;
801
-
802
- const choices = inputs.map(i => i.value);
803
-
804
- function setHighlightByIndex(idx) {
805
- const n = choices.length;
806
- const pct = 100 / n;
807
- highlight.style.width = `calc(${pct}% - 6px)`;
808
- highlight.style.transform = `translateX(${idx * 100}%)`;
809
- }
810
-
811
- function setCheckedByValue(val, shouldTrigger=false) {
812
- const idx = Math.max(0, choices.indexOf(val));
813
- inputs.forEach((inp, i) => { inp.checked = (i === idx); });
814
- setHighlightByIndex(idx);
815
- props.value = choices[idx];
816
- if (shouldTrigger) trigger('change', props.value);
817
- }
818
-
819
- setCheckedByValue(props.value ?? choices[0], false);
820
-
821
- inputs.forEach((inp) => {
822
- inp.addEventListener('change', () => setCheckedByValue(inp.value, true));
823
- });
824
- })();
825
- """
826
-
827
- super().__init__(value=value, html_template=html_template, js_on_load=js_on_load, **kwargs)
828
 
829
  def apply_gpu_duration(val: str):
830
  try:
831
- return int(val)
832
  except Exception:
833
  return 60
834
 
 
835
  MODEL_ID_F = "FireRedTeam/FireRed-OCR"
836
  processor_f = AutoProcessor.from_pretrained(MODEL_ID_F, trust_remote_code=True)
837
  model_f = Qwen3VLForConditionalGeneration.from_pretrained(
838
  MODEL_ID_F,
839
- attn_implementation="kernels-community/flash-attn2",
840
  trust_remote_code=True,
841
- torch_dtype=torch.float16
842
  ).to(device).eval()
843
 
844
  MODEL_ID_M = "nanonets/Nanonets-OCR-s"
845
  processor_m = AutoProcessor.from_pretrained(MODEL_ID_M, trust_remote_code=True)
846
  model_m = Qwen2_5_VLForConditionalGeneration.from_pretrained(
847
  MODEL_ID_M,
848
- attn_implementation="kernels-community/flash-attn2",
849
  trust_remote_code=True,
850
- torch_dtype=torch.float16
851
  ).to(device).eval()
852
 
853
  MODEL_ID_G = "echo840/MonkeyOCR"
854
  SUBFOLDER = "Recognition"
855
- processor_g = AutoProcessor.from_pretrained(MODEL_ID_G, trust_remote_code=True, subfolder=SUBFOLDER)
 
 
 
 
856
  model_g = Qwen2_5_VLForConditionalGeneration.from_pretrained(
857
  MODEL_ID_G,
858
- attn_implementation="kernels-community/flash-attn2",
859
  trust_remote_code=True,
860
  subfolder=SUBFOLDER,
861
- torch_dtype=torch.float16
862
  ).to(device).eval()
863
 
864
  MODEL_ID_L = "scb10x/typhoon-ocr-7b"
865
  processor_l = AutoProcessor.from_pretrained(MODEL_ID_L, trust_remote_code=True)
866
  model_l = Qwen2_5_VLForConditionalGeneration.from_pretrained(
867
  MODEL_ID_L,
868
- attn_implementation="kernels-community/flash-attn2",
869
  trust_remote_code=True,
870
- torch_dtype=torch.float16
871
  ).to(device).eval()
872
 
873
  MODEL_ID_X = "ds4sd/SmolDocling-256M-preview"
@@ -875,18 +96,19 @@ processor_x = AutoProcessor.from_pretrained(MODEL_ID_X, trust_remote_code=True)
875
  model_x = AutoModelForVision2Seq.from_pretrained(
876
  MODEL_ID_X,
877
  trust_remote_code=True,
878
- torch_dtype=torch.float16
879
  ).to(device).eval()
880
 
881
  MODEL_ID_N = "Kwai-Keye/Thyme-RL"
882
  processor_n = AutoProcessor.from_pretrained(MODEL_ID_N, trust_remote_code=True)
883
  model_n = Qwen2_5_VLForConditionalGeneration.from_pretrained(
884
  MODEL_ID_N,
885
- attn_implementation="kernels-community/flash-attn2",
886
  trust_remote_code=True,
887
- torch_dtype=torch.float16
888
  ).to(device).eval()
889
 
 
890
  def add_random_padding(image, min_percent=0.1, max_percent=0.10):
891
  image = image.convert("RGB")
892
  width, height = image.size
@@ -895,7 +117,9 @@ def add_random_padding(image, min_percent=0.1, max_percent=0.10):
895
  pad_w = int(width * pad_w_percent)
896
  pad_h = int(height * pad_h_percent)
897
  corner_pixel = image.getpixel((0, 0))
898
- return ImageOps.expand(image, border=(pad_w, pad_h, pad_w, pad_h), fill=corner_pixel)
 
 
899
 
900
  def normalize_values(text, target_max=500):
901
  def normalize_list(values):
@@ -908,7 +132,9 @@ def normalize_values(text, target_max=500):
908
  return "".join([f"<loc_{num}>" for num in normalized])
909
 
910
  pattern = r"\[([\d\.\s,]+)\]"
911
- return re.sub(pattern, process_match, text)
 
 
912
 
913
  def calc_timeout_image(model_name: str, text: str, image: Image.Image,
914
  max_new_tokens: int, temperature: float, top_p: float,
@@ -918,6 +144,23 @@ def calc_timeout_image(model_name: str, text: str, image: Image.Image,
918
  except Exception:
919
  return 60
920
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
921
  @spaces.GPU(duration=calc_timeout_image)
922
  def generate_image(model_name: str, text: str, image: Image.Image,
923
  max_new_tokens: int = 1024,
@@ -926,31 +169,24 @@ def generate_image(model_name: str, text: str, image: Image.Image,
926
  top_k: int = 50,
927
  repetition_penalty: float = 1.2,
928
  gpu_timeout: int = 60):
929
- if model_name == "Nanonets-OCR-s":
930
- processor, model = processor_m, model_m
931
- elif model_name == "MonkeyOCR-Recognition":
932
- processor, model = processor_g, model_g
933
- elif model_name == "SmolDocling-256M-preview":
934
- processor, model = processor_x, model_x
935
- elif model_name == "Typhoon-OCR-7B":
936
- processor, model = processor_l, model_l
937
- elif model_name == "Thyme-RL":
938
- processor, model = processor_n, model_n
939
- elif model_name == "FireRed-OCR":
940
- processor, model = processor_f, model_f
941
- else:
942
- yield "Invalid model selected.", "Invalid model selected."
943
  return
944
 
945
  if image is None:
946
- yield "Please upload an image.", "Please upload an image."
947
  return
948
 
949
  if not text or not str(text).strip():
950
- yield "Please enter a query.", "Please enter a query."
951
  return
952
 
953
- images = [image]
 
954
 
955
  if model_name == "SmolDocling-256M-preview":
956
  if "OTSL" in text or "code" in text:
@@ -958,45 +194,53 @@ def generate_image(model_name: str, text: str, image: Image.Image,
958
  if "OCR at text at" in text or "Identify element" in text or "formula" in text:
959
  text = normalize_values(text, target_max=500)
960
 
961
- messages = [{
962
- "role": "user",
963
- "content": [{"type": "image"} for _ in images] + [{"type": "text", "text": text}]
964
- }]
965
-
966
- prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
967
- inputs = processor(text=prompt, images=images, return_tensors="pt").to(device)
968
-
969
- streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
970
- generation_kwargs = {
971
- **inputs,
972
- "streamer": streamer,
973
- "max_new_tokens": int(max_new_tokens),
974
- "temperature": float(temperature),
975
- "top_p": float(top_p),
976
- "top_k": int(top_k),
977
- "repetition_penalty": float(repetition_penalty),
978
- }
979
-
980
- thread = Thread(target=model.generate, kwargs=generation_kwargs)
981
- thread.start()
982
 
983
- buffer = ""
984
- for new_text in streamer:
985
- buffer += new_text.replace("<|im_end|>", "")
986
- yield buffer, buffer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
987
 
988
- if model_name == "SmolDocling-256M-preview":
989
- cleaned_output = buffer.replace("<end_of_utterance>", "").strip()
990
- if any(tag in cleaned_output for tag in ["<doctag>", "<otsl>", "<code>", "<chart>", "<formula>"]):
991
- if "<chart>" in cleaned_output:
992
- cleaned_output = cleaned_output.replace("<chart>", "<otsl>").replace("</chart>", "</otsl>")
993
- cleaned_output = re.sub(r'(<loc_500>)(?!.*<loc_500>)<[^>]+>', r'\1', cleaned_output)
994
- doctags_doc = DocTagsDocument.from_doctags_and_image_pairs([cleaned_output], images)
995
- doc = DoclingDocument.load_from_doctags(doctags_doc, document_name="Document")
996
- markdown_output = doc.export_to_markdown()
997
- yield buffer, markdown_output
998
- else:
999
- yield buffer, cleaned_output
1000
 
1001
  image_examples = [
1002
  ["Generate Markdown", "examples/6.jpg"],
@@ -1007,133 +251,456 @@ image_examples = [
1007
  ["Convert this page to docling", "examples/3.jpg"],
1008
  ]
1009
 
1010
- def make_thumb_b64(path, max_dim=360):
1011
- if not os.path.exists(path):
1012
- return ""
1013
- try:
1014
- import base64
1015
- from io import BytesIO
1016
- img = Image.open(path).convert("RGB")
1017
- img.thumbnail((max_dim, max_dim))
1018
- buf = BytesIO()
1019
- img.save(buf, format="JPEG", quality=75)
1020
- return f"data:image/jpeg;base64,{base64.b64encode(buf.getvalue()).decode()}"
1021
- except Exception as e:
1022
- print(f"Example thumbnail error for {path}: {e}")
1023
- return ""
1024
 
1025
  def encode_full_image(path):
1026
  if not os.path.exists(path):
1027
  return ""
1028
  try:
1029
- import base64
1030
  with open(path, "rb") as f:
1031
  data = f.read()
1032
  ext = path.rsplit(".", 1)[-1].lower()
1033
  mime = {"jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png", "webp": "image/webp"}.get(ext, "image/jpeg")
1034
  return f"data:{mime};base64,{base64.b64encode(data).decode()}"
1035
  except Exception as e:
1036
- print(f"Example encode error for {path}: {e}")
1037
  return ""
1038
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1039
  def build_example_cards_html():
1040
  cards = ""
1041
- for i, item in enumerate(image_examples):
1042
- prompt_text, path = item
1043
- thumb = make_thumb_b64(path)
1044
- prompt_short = html.escape(prompt_text[:80] + ("..." if len(prompt_text) > 80 else ""))
1045
- image_html = f'<img class="example-thumb" src="{thumb}" alt="example">' if thumb else '<div class="example-thumb"></div>'
1046
  cards += f"""
1047
  <div class="example-card" data-idx="{i}">
1048
- {image_html}
1049
- <div class="example-meta">
1050
- <span class="example-badge">Example {i+1}</span>
1051
- </div>
1052
- <div class="example-prompt">{prompt_short}</div>
1053
  </div>
1054
  """
1055
  return cards
1056
 
 
1057
  def load_example_data(idx_str):
1058
  try:
1059
  idx = int(float(idx_str)) if idx_str and str(idx_str).strip() else -1
1060
- except (ValueError, TypeError):
1061
  idx = -1
1062
 
1063
  if idx < 0 or idx >= len(image_examples):
1064
- return json.dumps({"status": "error", "query": "", "image": "", "name": ""})
1065
 
1066
- query, path = image_examples[idx]
1067
- b64 = encode_full_image(path)
1068
  if not b64:
1069
- return json.dumps({"status": "error", "query": "", "image": "", "name": ""})
 
1070
 
1071
- return json.dumps({
1072
- "status": "ok",
1073
- "query": query,
1074
- "image": b64,
1075
- "name": os.path.basename(path)
1076
- })
1077
 
1078
  EXAMPLE_CARDS_HTML = build_example_cards_html()
1079
 
1080
- VISION_LOGO_SVG = """
1081
- <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
1082
- <path d="M12 5C6.5 5 2.2 8.4 1 12c1.2 3.6 5.5 7 11 7s9.8-3.4 11-7c-1.2-3.6-5.5-7-11-7zm0 11a4 4 0 1 1 0-8 4 4 0 0 1 0 8z"/>
1083
- <circle cx="12" cy="12" r="2.2"/>
 
 
 
 
 
 
 
 
 
 
1084
  </svg>
1085
  """
1086
 
1087
- UPLOAD_SVG = """
1088
- <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
1089
- <path d="M12 3l5 5h-3v7h-4V8H7l5-5z"/>
1090
- <path d="M4 17h16v4H4z"/>
1091
- </svg>
1092
- """
1093
 
1094
- REMOVE_SVG = """
1095
- <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
1096
- <path d="M7 4h10l1 2h4v2H2V6h4l1-2zm1 6h2v8H8v-8zm6 0h2v8h-2v-8zM6 8h12l-1 12H7L6 8z"/>
1097
- </svg>
1098
- """
 
 
 
 
 
1099
 
1100
- PLAY_SVG = """
1101
- <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
1102
- <path d="M8 5v14l11-7z"/>
1103
- </svg>
1104
- """
 
 
 
 
1105
 
1106
- DOWNLOAD_SVG = """
1107
- <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
1108
- <path d="M11 3h2v9h3l-4 4-4-4h3z"/>
1109
- <path d="M4 18h16v3H4z"/>
1110
- </svg>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1111
  """
1112
 
 
 
 
 
1113
  gallery_js = r"""
1114
  () => {
1115
  function init() {
1116
- if (window.__ocrInitDone) return;
1117
 
1118
- const fileInput = document.getElementById('custom-file-input');
1119
- const uploadZone = document.getElementById('upload-zone');
1120
  const uploadClick = document.getElementById('upload-click-area');
 
1121
  const previewWrap = document.getElementById('image-preview-wrap');
1122
- const previewImg = document.getElementById('image-preview-img');
1123
- const emptyState = document.getElementById('upload-empty');
1124
- const replaceBtn = document.getElementById('btn-replace-image');
1125
- const clearBtn = document.getElementById('btn-clear-image');
1126
  const queryInput = document.getElementById('custom-query-input');
1127
- const runBtn = document.getElementById('custom-run-btn');
1128
- const modelOptions = document.querySelectorAll('.model-option');
 
1129
 
1130
- if (!fileInput || !uploadZone || !queryInput) {
1131
  setTimeout(init, 250);
1132
  return;
1133
  }
1134
 
1135
- window.__ocrInitDone = true;
1136
- let uploadedImage = null;
 
1137
  let toastTimer = null;
1138
 
1139
  function showToast(message, type) {
@@ -1142,23 +709,27 @@ function init() {
1142
  toast = document.createElement('div');
1143
  toast.id = 'app-toast';
1144
  toast.className = 'toast-notification';
1145
- toast.innerHTML = '<span class="toast-text"></span>';
1146
  document.body.appendChild(toast);
1147
  }
 
 
1148
  toast.className = 'toast-notification ' + (type || 'error');
1149
- toast.querySelector('.toast-text').textContent = message;
 
 
 
1150
  if (toastTimer) clearTimeout(toastTimer);
1151
  void toast.offsetWidth;
1152
  toast.classList.add('visible');
1153
- toastTimer = setTimeout(() => toast.classList.remove('visible'), 3200);
1154
  }
1155
  window.__showToast = showToast;
1156
 
1157
- function flashError(el) {
1158
- if (!el) return;
1159
- el.classList.add('error-flash');
1160
- el.focus();
1161
- setTimeout(() => el.classList.remove('error-flash'), 800);
1162
  }
1163
 
1164
  function setGradioValue(containerId, value) {
@@ -1177,81 +748,98 @@ function init() {
1177
  }
1178
  window.__setGradioValue = setGradioValue;
1179
 
1180
- function syncPrompt() {
1181
- setGradioValue('query-gradio-input', queryInput.value || '');
 
 
 
 
 
 
 
 
 
 
 
 
 
1182
  }
1183
 
1184
- function syncImage() {
1185
- setGradioValue('hidden-image-b64', uploadedImage ? uploadedImage.b64 : '');
1186
- const status = document.getElementById('sb-image-status');
1187
- if (status) status.textContent = uploadedImage ? 'Image loaded' : 'No image';
1188
  }
1189
 
1190
- function renderImageState() {
1191
- const actions = document.getElementById('preview-actions');
1192
- if (uploadedImage && uploadedImage.b64) {
1193
- if (emptyState) emptyState.style.display = 'none';
1194
- if (previewWrap) previewWrap.classList.add('visible');
1195
- if (previewImg) previewImg.src = uploadedImage.b64;
1196
- if (actions) actions.classList.add('visible');
1197
- } else {
1198
- if (emptyState) emptyState.style.display = '';
1199
- if (previewWrap) previewWrap.classList.remove('visible');
1200
- if (previewImg) previewImg.removeAttribute('src');
1201
- if (actions) actions.classList.remove('visible');
1202
- }
1203
- syncImage();
1204
  }
1205
 
1206
- function setImage(b64, name) {
1207
- uploadedImage = { b64, name: name || 'image.png' };
1208
- renderImageState();
 
1209
  }
1210
- window.__setImage = setImage;
1211
 
1212
  function clearImage() {
1213
- uploadedImage = null;
1214
- renderImageState();
 
1215
  }
1216
- window.__clearImage = clearImage;
1217
 
1218
- function processFile(file) {
1219
- if (!file) return;
1220
- if (!file.type || !file.type.startsWith('image/')) {
1221
- showToast('Please upload a valid image file.', 'error');
1222
  return;
1223
  }
1224
  const reader = new FileReader();
1225
- reader.onload = (e) => setImage(e.target.result, file.name);
1226
  reader.readAsDataURL(file);
1227
  }
1228
 
1229
- fileInput.addEventListener('change', (e) => {
1230
- const f = e.target.files && e.target.files[0] ? e.target.files[0] : null;
1231
- processFile(f);
1232
- e.target.value = '';
1233
- });
1234
 
1235
- if (uploadClick) uploadClick.addEventListener('click', () => fileInput.click());
1236
- if (replaceBtn) replaceBtn.addEventListener('click', () => fileInput.click());
1237
- if (clearBtn) clearBtn.addEventListener('click', () => clearImage());
1238
-
1239
- uploadZone.addEventListener('dragover', (e) => {
1240
- e.preventDefault();
1241
- uploadZone.classList.add('drag-over');
1242
- });
1243
- uploadZone.addEventListener('dragleave', (e) => {
1244
  e.preventDefault();
1245
- uploadZone.classList.remove('drag-over');
 
1246
  });
1247
- uploadZone.addEventListener('drop', (e) => {
1248
- e.preventDefault();
1249
- uploadZone.classList.remove('drag-over');
1250
- const f = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0] ? e.dataTransfer.files[0] : null;
1251
- processFile(f);
 
 
 
 
 
 
 
 
 
 
 
 
1252
  });
1253
 
1254
- queryInput.addEventListener('input', syncPrompt);
 
 
 
 
 
 
 
 
 
1255
 
1256
  function syncSlider(customId, gradioId) {
1257
  const slider = document.getElementById(customId);
@@ -1278,62 +866,66 @@ function init() {
1278
  syncSlider('custom-top-k', 'gradio-top-k');
1279
  syncSlider('custom-repetition-penalty', 'gradio-repetition-penalty');
1280
 
1281
- function setModelValue(value) {
1282
- document.querySelectorAll('.model-option').forEach(el => {
1283
- el.classList.toggle('active', el.getAttribute('data-value') === value);
1284
- });
1285
- setGradioValue('gradio-model-choice', value);
1286
- const status = document.getElementById('sb-model-name');
1287
- if (status) status.textContent = value;
1288
  }
1289
- window.__setModelValue = setModelValue;
1290
 
1291
- modelOptions.forEach(el => {
1292
- el.addEventListener('click', () => {
1293
- const value = el.getAttribute('data-value');
1294
- setModelValue(value);
1295
- });
1296
- });
 
 
 
1297
 
1298
  function validateBeforeRun() {
1299
- const query = (queryInput.value || '').trim();
1300
- if (!uploadedImage) {
1301
- showToast('Please upload an image.', 'error');
 
 
 
1302
  return false;
1303
  }
1304
- if (!query) {
1305
- showToast('Please enter a query.', 'warning');
1306
- flashError(queryInput);
1307
  return false;
1308
  }
1309
- if (query.length > 8000) {
1310
- showToast('Query is too long.', 'error');
1311
- flashError(queryInput);
1312
  return false;
1313
  }
1314
- return true;
1315
- }
1316
 
1317
- function showLoader() {
1318
- const l = document.getElementById('output-loader');
1319
- if (l) l.classList.add('active');
1320
- const sb = document.getElementById('sb-run-status');
1321
- if (sb) sb.textContent = 'Processing';
1322
- }
1323
- function hideLoader() {
1324
- const l = document.getElementById('output-loader');
1325
- if (l) l.classList.remove('active');
1326
- const sb = document.getElementById('sb-run-status');
1327
- if (sb) sb.textContent = 'Done';
1328
  }
1329
- window.__showLoader = showLoader;
1330
- window.__hideLoader = hideLoader;
1331
 
1332
- window.__setQuery = function(val) {
1333
- queryInput.value = val || '';
1334
- syncPrompt();
 
 
 
 
 
 
 
 
1335
  };
1336
 
 
 
1337
  document.querySelectorAll('.example-card[data-idx]').forEach(card => {
1338
  card.addEventListener('click', () => {
1339
  const idx = card.getAttribute('data-idx');
@@ -1342,37 +934,20 @@ function init() {
1342
  showToast('Loading example...', 'info');
1343
  setGradioValue('example-result-data', '');
1344
  setGradioValue('example-idx-input', idx);
1345
-
1346
  setTimeout(() => {
1347
  const btn = document.getElementById('example-load-btn');
1348
  if (btn) {
1349
- const realBtn = btn.querySelector('button');
1350
- if (realBtn) realBtn.click(); else btn.click();
1351
  }
1352
- }, 150);
1353
-
1354
- setTimeout(() => card.classList.remove('loading'), 10000);
1355
  });
1356
  });
1357
 
1358
- window.__clickRun = function() {
1359
- if (!validateBeforeRun()) return;
1360
- syncPrompt();
1361
- syncImage();
1362
- showLoader();
1363
- setTimeout(() => {
1364
- const btn = document.getElementById('gradio-run-btn');
1365
- if (!btn) return;
1366
- const realBtn = btn.querySelector('button');
1367
- if (realBtn) realBtn.click(); else btn.click();
1368
- }, 150);
1369
- };
1370
-
1371
- if (runBtn) runBtn.addEventListener('click', () => window.__clickRun());
1372
-
1373
- renderImageState();
1374
- syncPrompt();
1375
- setModelValue('FireRed-OCR');
1376
  }
1377
  init();
1378
  }
@@ -1380,112 +955,148 @@ init();
1380
 
1381
  wire_outputs_js = r"""
1382
  () => {
1383
- function watchOutputs() {
1384
- const rawContainer = document.getElementById('gradio-raw-output');
1385
- const formattedContainer = document.getElementById('gradio-formatted-output');
1386
- const rawViewer = document.getElementById('raw-output-view');
1387
- const formattedViewer = document.getElementById('formatted-output-view');
1388
- const dlBtn = document.getElementById('dl-btn-output');
1389
-
1390
- if (!rawContainer || !formattedContainer || !rawViewer || !formattedViewer) {
1391
- setTimeout(watchOutputs, 500);
1392
- return;
1393
- }
1394
-
1395
- function getValueFromContainer(container) {
1396
- const el = container.querySelector('textarea, input');
1397
- return el ? el.value : '';
1398
- }
1399
-
1400
- function sync() {
1401
- const rawVal = getValueFromContainer(rawContainer);
1402
- const formattedVal = getValueFromContainer(formattedContainer);
1403
-
1404
- rawViewer.value = rawVal || '';
1405
- formattedViewer.textContent = formattedVal || '';
1406
-
1407
- if ((rawVal && rawVal.trim()) || (formattedVal && formattedVal.trim())) {
1408
- if (dlBtn) dlBtn.classList.add('visible');
1409
  if (window.__hideLoader) window.__hideLoader();
 
 
 
1410
  }
1411
  }
1412
 
1413
- const obs1 = new MutationObserver(sync);
1414
- const obs2 = new MutationObserver(sync);
1415
- obs1.observe(rawContainer, {childList:true, subtree:true, characterData:true, attributes:true});
1416
- obs2.observe(formattedContainer, {childList:true, subtree:true, characterData:true, attributes:true});
1417
- setInterval(sync, 500);
1418
-
1419
- if (dlBtn) {
1420
- dlBtn.addEventListener('click', () => {
1421
- const rawVal = rawViewer.value || '';
1422
- const formattedVal = formattedViewer.textContent || '';
1423
- const content = [
1424
- '=== RAW OUTPUT STREAM ===',
1425
- rawVal,
1426
- '',
1427
- '=== FORMATTED OUTPUT ===',
1428
- formattedVal
1429
- ].join('\n');
1430
- const blob = new Blob([content], {type:'text/plain;charset=utf-8'});
1431
- const url = URL.createObjectURL(blob);
1432
- const a = document.createElement('a');
1433
- a.href = url;
1434
- a.download = 'multimodal_ocr2_output.txt';
1435
- document.body.appendChild(a);
1436
- a.click();
1437
- document.body.removeChild(a);
1438
- URL.revokeObjectURL(url);
1439
- });
1440
- }
1441
  }
1442
- watchOutputs();
1443
 
1444
  function watchExampleResults() {
1445
  const container = document.getElementById('example-result-data');
1446
- if (!container) {
1447
- setTimeout(watchExampleResults, 500);
1448
- return;
1449
- }
1450
 
1451
  let lastProcessed = '';
1452
 
1453
- function check() {
1454
- const el = container.querySelector('textarea, input');
1455
  if (!el) return;
1456
  const val = el.value;
1457
  if (!val || val === lastProcessed || val.length < 10) return;
1458
 
1459
  try {
1460
  const data = JSON.parse(val);
1461
- if (data.status === 'ok') {
1462
  lastProcessed = val;
1463
- if (window.__setQuery) window.__setQuery(data.query || '');
1464
- if (window.__setImage && data.image) window.__setImage(data.image, data.name || 'example.jpg');
 
1465
  document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));
1466
- if (window.__showToast) window.__showToast('Example loaded successfully.', 'info');
1467
- } else {
1468
  document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));
1469
- if (window.__showToast) window.__showToast('Could not load example.', 'error');
1470
  }
1471
- } catch (e) {
1472
  console.error('Example parse error:', e);
1473
  }
1474
  }
1475
 
1476
- const obs = new MutationObserver(check);
1477
  obs.observe(container, {childList:true, subtree:true, characterData:true, attributes:true});
1478
- setInterval(check, 500);
1479
  }
1480
  watchExampleResults();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1481
  }
1482
  """
1483
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1484
  with gr.Blocks() as demo:
1485
  hidden_image_b64 = gr.Textbox(value="", elem_id="hidden-image-b64", elem_classes="hidden-input", container=False)
1486
- query_input_hidden = gr.Textbox(value="", elem_id="query-gradio-input", elem_classes="hidden-input", container=False)
1487
-
1488
- model_choice = gr.Textbox(value="FireRed-OCR", elem_id="gradio-model-choice", elem_classes="hidden-input", container=False)
1489
 
1490
  max_new_tokens = gr.Slider(minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS, elem_id="gradio-max-new-tokens", elem_classes="hidden-input", container=False)
1491
  temperature = gr.Slider(minimum=0.1, maximum=4.0, step=0.1, value=0.6, elem_id="gradio-temperature", elem_classes="hidden-input", container=False)
@@ -1493,59 +1104,63 @@ with gr.Blocks() as demo:
1493
  top_k = gr.Slider(minimum=1, maximum=1000, step=1, value=50, elem_id="gradio-top-k", elem_classes="hidden-input", container=False)
1494
  repetition_penalty = gr.Slider(minimum=1.0, maximum=2.0, step=0.05, value=1.2, elem_id="gradio-repetition-penalty", elem_classes="hidden-input", container=False)
1495
 
1496
- raw_output_hidden = gr.Textbox(lines=10, elem_id="gradio-raw-output", elem_classes="hidden-input", container=False)
1497
- formatted_output_hidden = gr.Textbox(lines=10, elem_id="gradio-formatted-output", elem_classes="hidden-input", container=False)
1498
 
1499
  example_idx = gr.Textbox(value="", elem_id="example-idx-input", elem_classes="hidden-input", container=False)
1500
  example_result = gr.Textbox(value="", elem_id="example-result-data", elem_classes="hidden-input", container=False)
1501
  example_load_btn = gr.Button("Load Example", elem_id="example-load-btn")
1502
 
1503
- gpu_duration_state = gr.Number(value=60, visible=False)
1504
-
1505
  gr.HTML(f"""
1506
  <div class="app-shell">
1507
  <div class="app-header">
1508
  <div class="app-header-left">
1509
- <div class="app-logo">{VISION_LOGO_SVG}</div>
1510
- <div class="app-title">Multimodal OCR 2</div>
1511
- <div class="app-badge">Vision Based</div>
 
1512
  </div>
1513
  </div>
1514
 
1515
- <div class="app-main">
1516
- <div class="app-left">
1517
- <div class="panel">
1518
- <div class="panel-title">Query</div>
1519
- <div class="panel-body">
1520
- <label class="modern-label" for="custom-query-input">OCR / Extraction Prompt</label>
1521
- <textarea id="custom-query-input" class="modern-textarea" rows="3" placeholder="e.g. Perform OCR on the image precisely."></textarea>
1522
- </div>
1523
- </div>
 
1524
 
1525
- <div class="panel">
1526
- <div class="panel-title">Upload Image</div>
1527
- <div id="upload-zone" class="upload-zone">
1528
- <div id="upload-empty" class="upload-empty">
1529
- <div id="upload-click-area" class="upload-click-area">
1530
- <svg viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
1531
- <rect x="10" y="12" width="60" height="48" rx="8" stroke="#D3F527" stroke-width="2" stroke-dasharray="4 4"/>
1532
- <circle cx="30" cy="30" r="6" stroke="#D3F527" stroke-width="2" fill="rgba(211,245,39,.15)"/>
1533
- <path d="M18 52L32 38L42 46L54 32L66 52" stroke="#D3F527" stroke-width="2" fill="rgba(211,245,39,.10)"/>
1534
- <path d="M40 18V8M35 13H45" stroke="#D3F527" stroke-width="2" stroke-linecap="round"/>
1535
- </svg>
1536
- <div class="upload-main-text">Click or drag an image here</div>
1537
- <div class="upload-sub-text">Supports OCR, markdown extraction, structured reading, and document understanding.</div>
1538
- </div>
1539
- </div>
1540
- <div id="image-preview-wrap" class="preview-wrap">
1541
- <img id="image-preview-img" alt="uploaded image preview" />
1542
  </div>
1543
  </div>
1544
- <div id="preview-actions" class="preview-actions">
1545
- <button id="btn-replace-image" class="modern-btn">{UPLOAD_SVG} Replace Image</button>
1546
- <button id="btn-clear-image" class="modern-btn">{REMOVE_SVG} Clear Image</button>
1547
- </div>
1548
  <input id="custom-file-input" type="file" accept="image/*" style="display:none;" />
 
 
 
 
 
 
 
 
 
 
 
 
 
1549
  </div>
1550
 
1551
  <div class="examples-section">
@@ -1556,182 +1171,150 @@ with gr.Blocks() as demo:
1556
  </div>
1557
  </div>
1558
 
1559
- <div class="app-right">
1560
- <div class="panel">
1561
- <div class="panel-title">Select Model</div>
1562
- <div class="panel-body">
1563
- <div class="model-grid">
1564
- <button class="model-option active" data-value="FireRed-OCR">FireRed-OCR</button>
1565
- <button class="model-option" data-value="Nanonets-OCR-s">Nanonets-OCR-s</button>
1566
- <button class="model-option" data-value="MonkeyOCR-Recognition">MonkeyOCR-Recognition</button>
1567
- <button class="model-option" data-value="Thyme-RL">Thyme-RL</button>
1568
- <button class="model-option" data-value="Typhoon-OCR-7B">Typhoon-OCR-7B</button>
1569
- <button class="model-option" data-value="SmolDocling-256M-preview">SmolDocling-256M-preview</button>
 
 
 
 
 
 
 
 
1570
  </div>
1571
  </div>
1572
  </div>
1573
 
1574
- <div style="padding:16px 18px 4px;">
1575
- <button id="custom-run-btn" class="modern-btn primary">
1576
- {PLAY_SVG}
1577
- Run OCR
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1578
  </button>
1579
  </div>
1580
 
1581
- <div class="output-frame">
1582
- <div class="output-header">
1583
- <div class="output-title">Output</div>
1584
- <button id="dl-btn-output" class="out-download-btn">{DOWNLOAD_SVG} Save</button>
1585
  </div>
1586
- <div class="output-body">
1587
- <div id="output-loader" class="loader">
1588
  <div class="loader-spinner"></div>
1589
- <div class="loader-text">Processing image...</div>
 
 
 
 
1590
  </div>
1591
-
1592
- <div class="output-label">Raw Output Stream</div>
1593
- <textarea id="raw-output-view" class="output-raw" rows="10" readonly placeholder="Raw stream will appear here..."></textarea>
1594
-
1595
- <div class="output-label">Formatted Output</div>
1596
- <div id="formatted-output-view" class="formatted-output">Formatted output will appear here...</div>
1597
  </div>
1598
  </div>
1599
 
1600
  <div class="settings-group">
1601
- <div class="settings-group-title">Advanced Options</div>
1602
  <div class="settings-group-body">
1603
  <div class="slider-row">
1604
- <label>Max new tokens</label>
1605
  <input type="range" id="custom-max-new-tokens" min="1" max="{MAX_MAX_NEW_TOKENS}" step="1" value="{DEFAULT_MAX_NEW_TOKENS}">
1606
  <span class="slider-val" id="custom-max-new-tokens-val">{DEFAULT_MAX_NEW_TOKENS}</span>
1607
  </div>
1608
-
1609
  <div class="slider-row">
1610
  <label>Temperature</label>
1611
  <input type="range" id="custom-temperature" min="0.1" max="4.0" step="0.1" value="0.6">
1612
  <span class="slider-val" id="custom-temperature-val">0.6</span>
1613
  </div>
1614
-
1615
  <div class="slider-row">
1616
  <label>Top-p</label>
1617
  <input type="range" id="custom-top-p" min="0.05" max="1.0" step="0.05" value="0.9">
1618
  <span class="slider-val" id="custom-top-p-val">0.9</span>
1619
  </div>
1620
-
1621
  <div class="slider-row">
1622
  <label>Top-k</label>
1623
  <input type="range" id="custom-top-k" min="1" max="1000" step="1" value="50">
1624
  <span class="slider-val" id="custom-top-k-val">50</span>
1625
  </div>
1626
-
1627
  <div class="slider-row">
1628
- <label>Repetition penalty</label>
1629
  <input type="range" id="custom-repetition-penalty" min="1.0" max="2.0" step="0.05" value="1.2">
1630
  <span class="slider-val" id="custom-repetition-penalty-val">1.2</span>
1631
  </div>
1632
-
1633
- <div class="gpu-group">
1634
- <div class="gpu-title">GPU Duration (seconds)</div>
1635
- <div class="gpu-radio-mount"></div>
1636
- <div class="gpu-note">Higher GPU duration allows longer processing but uses more GPU quota.</div>
1637
- </div>
1638
  </div>
1639
  </div>
1640
-
1641
- <div class="exp-note">
1642
- Experimental OCR interface for multiple vision-language OCR backends.
1643
- </div>
1644
  </div>
1645
  </div>
1646
 
1647
- <div class="statusbar">
1648
- <div id="sb-image-status">No image</div>
1649
- <div class="status-chip" id="sb-model-name">FireRed-OCR</div>
1650
- <div class="status-chip" id="sb-run-status">Ready</div>
 
 
 
1651
  </div>
1652
  </div>
1653
  """)
1654
 
1655
- with gr.Group(elem_classes="gpu-radio-mount"):
1656
- radioanimated_gpu_duration = RadioAnimated(
1657
- choices=["60", "90", "120", "180", "240", "300"],
1658
- value="60",
1659
- elem_id="radioanimated_gpu_duration"
1660
- )
1661
-
1662
- gradio_run_btn = gr.Button("Run", elem_id="gradio-run-btn")
1663
 
1664
  demo.load(fn=None, js=gallery_js)
1665
  demo.load(fn=None, js=wire_outputs_js)
1666
 
1667
- example_load_btn.click(
1668
- fn=load_example_data,
1669
- inputs=[example_idx],
1670
- outputs=[example_result],
1671
- queue=False,
1672
- )
1673
-
1674
- radioanimated_gpu_duration.change(
1675
- fn=apply_gpu_duration,
1676
- inputs=radioanimated_gpu_duration,
1677
- outputs=[gpu_duration_state],
1678
- api_visibility="private"
1679
- )
1680
-
1681
- def b64_to_pil(data_url):
1682
- import base64
1683
- from io import BytesIO
1684
- if not data_url:
1685
- return None
1686
- try:
1687
- data = data_url.split(",", 1)[1] if "," in data_url else data_url
1688
- image_data = base64.b64decode(data)
1689
- return Image.open(BytesIO(image_data)).convert("RGB")
1690
- except Exception:
1691
- return None
1692
-
1693
- def run_bridge(model_name, query, image_b64, max_tokens, temp, tp, tk, rep_pen, gpu_seconds):
1694
- image = b64_to_pil(image_b64)
1695
- for raw, formatted in generate_image(
1696
- model_name=model_name,
1697
- text=query,
1698
- image=image,
1699
- max_new_tokens=max_tokens,
1700
- temperature=temp,
1701
- top_p=tp,
1702
- top_k=tk,
1703
- repetition_penalty=rep_pen,
1704
- gpu_timeout=gpu_seconds,
1705
- ):
1706
- yield raw, formatted
1707
-
1708
- gradio_run_btn.click(
1709
- fn=run_bridge,
1710
  inputs=[
1711
  model_choice,
1712
- query_input_hidden,
1713
  hidden_image_b64,
1714
  max_new_tokens,
1715
  temperature,
1716
  top_p,
1717
  top_k,
1718
  repetition_penalty,
1719
- gpu_duration_state,
1720
  ],
1721
- outputs=[raw_output_hidden, formatted_output_hidden],
1722
- js=r"""(model_name, query, image_b64, max_tokens, temp, tp, tk, rep_pen, gpu_seconds) => {
1723
- const queryEl = document.getElementById('custom-query-input');
1724
- const queryVal = queryEl ? queryEl.value : query;
1725
  const imgContainer = document.getElementById('hidden-image-b64');
1726
- let imgVal = image_b64;
1727
  if (imgContainer) {
1728
- const hiddenEl = imgContainer.querySelector('textarea, input');
1729
- if (hiddenEl) imgVal = hiddenEl.value;
1730
  }
1731
- return [model_name, queryVal, imgVal, max_tokens, temp, tp, tk, rep_pen, gpu_seconds];
1732
  }""",
1733
  )
1734
 
 
 
 
 
 
 
 
1735
  if __name__ == "__main__":
1736
  demo.queue(max_size=50).launch(
1737
  css=css,
 
1
  import os
2
+ import gc
3
+ import re
4
+ import ast
5
  import json
6
+ import html as html_lib
7
+ import random
8
+ import base64
9
+ from io import BytesIO
10
  from threading import Thread
11
 
12
  import gradio as gr
 
17
  from transformers import (
18
  Qwen2_5_VLForConditionalGeneration,
19
  Qwen3VLForConditionalGeneration,
 
20
  AutoProcessor,
21
+ AutoModelForVision2Seq,
22
  TextIteratorStreamer,
23
  )
24
 
25
  from docling_core.types.doc import DoclingDocument, DocTagsDocument
26
 
 
 
 
27
 
28
  MAX_MAX_NEW_TOKENS = 4096
29
  DEFAULT_MAX_NEW_TOKENS = 2048
30
  MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
31
 
32
  device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
33
+ dtype = torch.float16 if torch.cuda.is_available() else torch.float32
34
 
35
+ print("CUDA_VISIBLE_DEVICES =", os.environ.get("CUDA_VISIBLE_DEVICES"))
36
  print("torch.__version__ =", torch.__version__)
37
  print("Using device:", device)
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ def safe_empty_cache():
41
+ if torch.cuda.is_available():
42
+ torch.cuda.empty_cache()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  def apply_gpu_duration(val: str):
46
  try:
47
+ return int(str(val).strip())
48
  except Exception:
49
  return 60
50
 
51
+
52
  MODEL_ID_F = "FireRedTeam/FireRed-OCR"
53
  processor_f = AutoProcessor.from_pretrained(MODEL_ID_F, trust_remote_code=True)
54
  model_f = Qwen3VLForConditionalGeneration.from_pretrained(
55
  MODEL_ID_F,
56
+ attn_implementation="kernels-community/flash-attn2" if torch.cuda.is_available() else "eager",
57
  trust_remote_code=True,
58
+ torch_dtype=dtype,
59
  ).to(device).eval()
60
 
61
  MODEL_ID_M = "nanonets/Nanonets-OCR-s"
62
  processor_m = AutoProcessor.from_pretrained(MODEL_ID_M, trust_remote_code=True)
63
  model_m = Qwen2_5_VLForConditionalGeneration.from_pretrained(
64
  MODEL_ID_M,
65
+ attn_implementation="kernels-community/flash-attn2" if torch.cuda.is_available() else "eager",
66
  trust_remote_code=True,
67
+ torch_dtype=dtype,
68
  ).to(device).eval()
69
 
70
  MODEL_ID_G = "echo840/MonkeyOCR"
71
  SUBFOLDER = "Recognition"
72
+ processor_g = AutoProcessor.from_pretrained(
73
+ MODEL_ID_G,
74
+ trust_remote_code=True,
75
+ subfolder=SUBFOLDER,
76
+ )
77
  model_g = Qwen2_5_VLForConditionalGeneration.from_pretrained(
78
  MODEL_ID_G,
79
+ attn_implementation="kernels-community/flash-attn2" if torch.cuda.is_available() else "eager",
80
  trust_remote_code=True,
81
  subfolder=SUBFOLDER,
82
+ torch_dtype=dtype,
83
  ).to(device).eval()
84
 
85
  MODEL_ID_L = "scb10x/typhoon-ocr-7b"
86
  processor_l = AutoProcessor.from_pretrained(MODEL_ID_L, trust_remote_code=True)
87
  model_l = Qwen2_5_VLForConditionalGeneration.from_pretrained(
88
  MODEL_ID_L,
89
+ attn_implementation="kernels-community/flash-attn2" if torch.cuda.is_available() else "eager",
90
  trust_remote_code=True,
91
+ torch_dtype=dtype,
92
  ).to(device).eval()
93
 
94
  MODEL_ID_X = "ds4sd/SmolDocling-256M-preview"
 
96
  model_x = AutoModelForVision2Seq.from_pretrained(
97
  MODEL_ID_X,
98
  trust_remote_code=True,
99
+ torch_dtype=dtype,
100
  ).to(device).eval()
101
 
102
  MODEL_ID_N = "Kwai-Keye/Thyme-RL"
103
  processor_n = AutoProcessor.from_pretrained(MODEL_ID_N, trust_remote_code=True)
104
  model_n = Qwen2_5_VLForConditionalGeneration.from_pretrained(
105
  MODEL_ID_N,
106
+ attn_implementation="kernels-community/flash-attn2" if torch.cuda.is_available() else "eager",
107
  trust_remote_code=True,
108
+ torch_dtype=dtype,
109
  ).to(device).eval()
110
 
111
+
112
  def add_random_padding(image, min_percent=0.1, max_percent=0.10):
113
  image = image.convert("RGB")
114
  width, height = image.size
 
117
  pad_w = int(width * pad_w_percent)
118
  pad_h = int(height * pad_h_percent)
119
  corner_pixel = image.getpixel((0, 0))
120
+ padded_image = ImageOps.expand(image, border=(pad_w, pad_h, pad_w, pad_h), fill=corner_pixel)
121
+ return padded_image
122
+
123
 
124
  def normalize_values(text, target_max=500):
125
  def normalize_list(values):
 
132
  return "".join([f"<loc_{num}>" for num in normalized])
133
 
134
  pattern = r"\[([\d\.\s,]+)\]"
135
+ normalized_text = re.sub(pattern, process_match, text)
136
+ return normalized_text
137
+
138
 
139
  def calc_timeout_image(model_name: str, text: str, image: Image.Image,
140
  max_new_tokens: int, temperature: float, top_p: float,
 
144
  except Exception:
145
  return 60
146
 
147
+
148
+ def get_model_and_processor(model_name: str):
149
+ if model_name == "Nanonets-OCR-s":
150
+ return processor_m, model_m
151
+ elif model_name == "MonkeyOCR-Recognition":
152
+ return processor_g, model_g
153
+ elif model_name == "SmolDocling-256M-preview":
154
+ return processor_x, model_x
155
+ elif model_name == "Typhoon-OCR-7B":
156
+ return processor_l, model_l
157
+ elif model_name == "Thyme-RL":
158
+ return processor_n, model_n
159
+ elif model_name == "FireRed-OCR":
160
+ return processor_f, model_f
161
+ return None, None
162
+
163
+
164
  @spaces.GPU(duration=calc_timeout_image)
165
  def generate_image(model_name: str, text: str, image: Image.Image,
166
  max_new_tokens: int = 1024,
 
169
  top_k: int = 50,
170
  repetition_penalty: float = 1.2,
171
  gpu_timeout: int = 60):
172
+ gc.collect()
173
+ safe_empty_cache()
174
+
175
+ processor, model = get_model_and_processor(model_name)
176
+ if processor is None or model is None:
177
+ yield "Invalid model selected."
 
 
 
 
 
 
 
 
178
  return
179
 
180
  if image is None:
181
+ yield "Please upload an image."
182
  return
183
 
184
  if not text or not str(text).strip():
185
+ yield "Please enter a query."
186
  return
187
 
188
+ text = str(text).strip()
189
+ images = [image.convert("RGB")]
190
 
191
  if model_name == "SmolDocling-256M-preview":
192
  if "OTSL" in text or "code" in text:
 
194
  if "OCR at text at" in text or "Identify element" in text or "formula" in text:
195
  text = normalize_values(text, target_max=500)
196
 
197
+ try:
198
+ messages = [
199
+ {
200
+ "role": "user",
201
+ "content": [{"type": "image"} for _ in images] + [{"type": "text", "text": text}],
202
+ }
203
+ ]
204
+ prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
205
+ inputs = processor(text=prompt, images=images, return_tensors="pt").to(device)
206
+
207
+ streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
208
+ generation_kwargs = {
209
+ **inputs,
210
+ "streamer": streamer,
211
+ "max_new_tokens": int(max_new_tokens),
212
+ "temperature": float(temperature),
213
+ "top_p": float(top_p),
214
+ "top_k": int(top_k),
215
+ "repetition_penalty": float(repetition_penalty),
216
+ }
 
217
 
218
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
219
+ thread.start()
220
+
221
+ buffer = ""
222
+ for new_text in streamer:
223
+ buffer += new_text.replace("<|im_end|>", "")
224
+ yield buffer
225
+
226
+ if model_name == "SmolDocling-256M-preview":
227
+ cleaned_output = buffer.replace("<end_of_utterance>", "").strip()
228
+ if any(tag in cleaned_output for tag in ["<doctag>", "<otsl>", "<code>", "<chart>", "<formula>"]):
229
+ if "<chart>" in cleaned_output:
230
+ cleaned_output = cleaned_output.replace("<chart>", "<otsl>").replace("</chart>", "</otsl>")
231
+ cleaned_output = re.sub(r'(<loc_500>)(?!.*<loc_500>)<[^>]+>', r'\1', cleaned_output)
232
+ doctags_doc = DocTagsDocument.from_doctags_and_image_pairs([cleaned_output], images)
233
+ doc = DoclingDocument.load_from_doctags(doctags_doc, document_name="Document")
234
+ markdown_output = doc.export_to_markdown()
235
+ yield markdown_output
236
+ else:
237
+ yield cleaned_output
238
+ except Exception as e:
239
+ yield f"Error: {str(e)}"
240
+ finally:
241
+ gc.collect()
242
+ safe_empty_cache()
243
 
 
 
 
 
 
 
 
 
 
 
 
 
244
 
245
  image_examples = [
246
  ["Generate Markdown", "examples/6.jpg"],
 
251
  ["Convert this page to docling", "examples/3.jpg"],
252
  ]
253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
 
255
  def encode_full_image(path):
256
  if not os.path.exists(path):
257
  return ""
258
  try:
 
259
  with open(path, "rb") as f:
260
  data = f.read()
261
  ext = path.rsplit(".", 1)[-1].lower()
262
  mime = {"jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png", "webp": "image/webp"}.get(ext, "image/jpeg")
263
  return f"data:{mime};base64,{base64.b64encode(data).decode()}"
264
  except Exception as e:
265
+ print(f"Encode error for {path}: {e}")
266
  return ""
267
 
268
+
269
+ def make_thumb_b64(path, max_dim=240):
270
+ if not os.path.exists(path):
271
+ return ""
272
+ try:
273
+ img = Image.open(path).convert("RGB")
274
+ img.thumbnail((max_dim, max_dim))
275
+ buf = BytesIO()
276
+ img.save(buf, format="JPEG", quality=70)
277
+ return f"data:image/jpeg;base64,{base64.b64encode(buf.getvalue()).decode()}"
278
+ except Exception as e:
279
+ print(f"Thumbnail error for {path}: {e}")
280
+ return ""
281
+
282
+
283
  def build_example_cards_html():
284
  cards = ""
285
+ for i, ex in enumerate(image_examples):
286
+ query, img_path = ex
287
+ thumb = make_thumb_b64(img_path)
288
+ thumb_html = f'<img src="{thumb}" alt="example">' if thumb else '<div class="example-thumb-placeholder">Preview</div>'
289
+ short_query = html_lib.escape(query[:80]) + ("..." if len(query) > 80 else "")
290
  cards += f"""
291
  <div class="example-card" data-idx="{i}">
292
+ <div class="example-thumbs">{thumb_html}</div>
293
+ <div class="example-meta"><span class="example-badge">Example {i+1}</span></div>
294
+ <div class="example-prompt-text">{short_query}</div>
 
 
295
  </div>
296
  """
297
  return cards
298
 
299
+
300
  def load_example_data(idx_str):
301
  try:
302
  idx = int(float(idx_str)) if idx_str and str(idx_str).strip() else -1
303
+ except Exception:
304
  idx = -1
305
 
306
  if idx < 0 or idx >= len(image_examples):
307
+ return json.dumps({"image": "", "query": "", "status": "error"})
308
 
309
+ query, img_path = image_examples[idx]
310
+ b64 = encode_full_image(img_path)
311
  if not b64:
312
+ return json.dumps({"image": "", "query": "", "status": "error"})
313
+ return json.dumps({"image": b64, "query": query, "status": "ok"})
314
 
 
 
 
 
 
 
315
 
316
  EXAMPLE_CARDS_HTML = build_example_cards_html()
317
 
318
+ VISION_OCR_LOGO = """
319
+ <svg viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
320
+ <defs>
321
+ <linearGradient id="visionGrad" x1="0%" y1="0%" x2="100%" y2="100%">
322
+ <stop offset="0%" stop-color="#FF6A3D"/>
323
+ <stop offset="100%" stop-color="#FF4500"/>
324
+ </linearGradient>
325
+ </defs>
326
+ <rect x="8" y="10" width="48" height="36" rx="10" fill="url(#visionGrad)" opacity="0.18" stroke="#FF4500" stroke-width="2.5"/>
327
+ <path d="M32 20c-11 0-18.5 10.5-18.5 10.5S21 41 32 41s18.5-10.5 18.5-10.5S43 20 32 20z" fill="none" stroke="#FF4500" stroke-width="3" stroke-linejoin="round"/>
328
+ <circle cx="32" cy="30.5" r="6.2" fill="none" stroke="#FF4500" stroke-width="3"/>
329
+ <circle cx="34.5" cy="28" r="1.7" fill="#FF4500"/>
330
+ <path d="M18 52h28" stroke="#FF4500" stroke-width="3" stroke-linecap="round"/>
331
+ <path d="M18 58h20" stroke="#FF4500" stroke-width="3" stroke-linecap="round" opacity="0.8"/>
332
  </svg>
333
  """
334
 
335
+ css = r"""
336
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap');
 
 
 
 
337
 
338
+ *{box-sizing:border-box;margin:0;padding:0}
339
+ body,.gradio-container{
340
+ background:#0f0f13!important;
341
+ font-family:'Inter',system-ui,-apple-system,sans-serif!important;
342
+ font-size:14px!important;
343
+ color:#e7e5e4!important;
344
+ min-height:100vh;
345
+ }
346
+ footer{display:none!important}
347
+ .hidden-input{display:none!important;height:0!important;overflow:hidden!important;margin:0!important;padding:0!important}
348
 
349
+ #gradio-run-btn{
350
+ position:absolute;left:-9999px;top:-9999px;width:1px;height:1px;
351
+ opacity:0.01;pointer-events:none;overflow:hidden;
352
+ }
353
+ #example-load-btn{
354
+ position:absolute!important;left:-9999px!important;top:-9999px!important;
355
+ width:1px!important;height:1px!important;opacity:0.01!important;
356
+ pointer-events:none!important;overflow:hidden!important;
357
+ }
358
 
359
+ .app-shell{
360
+ background:#18181b;
361
+ border:1px solid #292524;
362
+ border-radius:18px;
363
+ margin:12px auto;
364
+ max-width:1400px;
365
+ overflow:hidden;
366
+ box-shadow:0 25px 50px -12px rgba(0,0,0,.6),0 0 0 1px rgba(255,255,255,.02);
367
+ }
368
+ .app-header{
369
+ background:linear-gradient(135deg,#18181b,#1f1b18);
370
+ border-bottom:1px solid #292524;
371
+ padding:14px 24px;
372
+ display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;
373
+ }
374
+ .app-header-left{display:flex;align-items:center;gap:12px}
375
+ .app-logo{
376
+ width:42px;height:42px;
377
+ background:linear-gradient(135deg,#FF7A4D,#FF4500,#E63E00);
378
+ border-radius:12px;
379
+ display:flex;align-items:center;justify-content:center;
380
+ box-shadow:0 4px 12px rgba(255,69,0,.35);
381
+ }
382
+ .app-logo svg{width:24px;height:24px}
383
+ .app-title{
384
+ font-size:19px;font-weight:800;
385
+ background:linear-gradient(135deg,#fff7ed,#fdba74);
386
+ -webkit-background-clip:text;-webkit-text-fill-color:transparent;
387
+ letter-spacing:-.3px;
388
+ }
389
+ .app-badge{
390
+ font-size:11px;font-weight:700;padding:3px 10px;border-radius:999px;
391
+ background:rgba(255,69,0,.12);color:#ff8a65;border:1px solid rgba(255,69,0,.25);letter-spacing:.3px;
392
+ }
393
+ .app-badge.fast{
394
+ background:rgba(249,115,22,.12);color:#fb923c;border:1px solid rgba(249,115,22,.22)
395
+ }
396
+
397
+ .app-toolbar{
398
+ background:#18181b;border-bottom:1px solid #292524;padding:8px 16px;
399
+ display:flex;gap:8px;align-items:center;flex-wrap:wrap;
400
+ }
401
+ .tb-sep{width:1px;height:28px;background:#292524;margin:0 8px}
402
+ .modern-tb-btn{
403
+ display:inline-flex;align-items:center;justify-content:center;gap:6px;
404
+ min-width:32px;height:36px;background:transparent;border:1px solid transparent;
405
+ border-radius:8px;cursor:pointer;font-size:13px;font-weight:600;padding:0 12px;
406
+ font-family:'Inter',sans-serif;color:#fff!important;transition:all .15s ease;
407
+ }
408
+ .modern-tb-btn:hover{background:rgba(255,69,0,.12);border-color:rgba(255,69,0,.28)}
409
+ .modern-tb-btn:active,.modern-tb-btn.active{background:rgba(255,69,0,.2);border-color:rgba(255,69,0,.38)}
410
+ .modern-tb-btn .tb-label{font-size:13px;color:#fff!important;font-weight:600}
411
+ .modern-tb-btn .tb-svg{width:15px;height:15px;flex-shrink:0;color:#fff!important}
412
+ .modern-tb-btn .tb-svg,.modern-tb-btn .tb-svg *{stroke:#fff!important;fill:none!important}
413
+ .tb-info{font-family:'JetBrains Mono',monospace;font-size:12px;color:#a8a29e;padding:0 8px;display:flex;align-items:center}
414
+
415
+ .app-main-row{display:flex;gap:0;flex:1;overflow:hidden}
416
+ .app-main-left{flex:1;display:flex;flex-direction:column;min-width:0;border-right:1px solid #292524}
417
+ .app-main-right{width:460px;display:flex;flex-direction:column;flex-shrink:0;background:#18181b}
418
+
419
+ #image-drop-zone{
420
+ position:relative;background:#09090b;min-height:430px;max-height:430px;overflow:hidden;
421
+ }
422
+ #image-drop-zone.drag-over{outline:2px solid #FF4500;outline-offset:-2px;background:rgba(255,69,0,.04)}
423
+
424
+ .upload-prompt-modern{
425
+ position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);z-index:20
426
+ }
427
+ .upload-click-area{
428
+ display:flex;flex-direction:column;align-items:center;justify-content:center;
429
+ cursor:pointer;padding:36px 52px;border:2px dashed #44403c;border-radius:16px;
430
+ background:rgba(255,69,0,.03);transition:all .2s ease;gap:8px;
431
+ }
432
+ .upload-click-area:hover{background:rgba(255,69,0,.08);border-color:#FF4500;transform:scale(1.02)}
433
+ .upload-click-area:active{background:rgba(255,69,0,.12);transform:scale(.98)}
434
+ .upload-click-area svg{width:84px;height:84px}
435
+ .upload-main-text{color:#d6d3d1;font-size:15px;font-weight:600;margin-top:4px}
436
+ .upload-sub-text{color:#78716c;font-size:12px;text-align:center;max-width:360px}
437
+
438
+ .image-preview-wrap{
439
+ width:100%;height:100%;display:none;align-items:center;justify-content:center;padding:16px;
440
+ }
441
+ .image-preview-wrap.visible{display:flex}
442
+ .image-preview-card{
443
+ position:relative;
444
+ width:100%;height:100%;
445
+ border-radius:14px;border:1px solid #292524;background:#111113;overflow:hidden;
446
+ display:flex;align-items:center;justify-content:center;
447
+ }
448
+ .image-preview-card img{
449
+ max-width:100%;max-height:100%;object-fit:contain;display:block;
450
+ }
451
+ .image-remove-btn{
452
+ position:absolute;top:10px;right:10px;width:34px;height:34px;border:none;border-radius:50%;
453
+ background:rgba(0,0,0,.72);color:#fff;cursor:pointer;font-size:14px;font-weight:700;
454
+ display:flex;align-items:center;justify-content:center;transition:all .15s ease;
455
+ border:1px solid rgba(255,255,255,.1);
456
+ }
457
+ .image-remove-btn:hover{background:#FF4500;border-color:#FF4500}
458
+
459
+ .hint-bar{
460
+ background:rgba(255,69,0,.05);border-top:1px solid #292524;border-bottom:1px solid #292524;
461
+ padding:10px 20px;font-size:13px;color:#d6d3d1;line-height:1.7;
462
+ }
463
+ .hint-bar b{color:#ff8a65;font-weight:700}
464
+ .hint-bar kbd{
465
+ display:inline-block;padding:1px 6px;background:#292524;border:1px solid #44403c;
466
+ border-radius:4px;font-family:'JetBrains Mono',monospace;font-size:11px;color:#d6d3d1;
467
+ }
468
+
469
+ .examples-section{border-top:1px solid #292524;padding:12px 16px}
470
+ .examples-title{
471
+ font-size:12px;font-weight:700;color:#a8a29e;text-transform:uppercase;
472
+ letter-spacing:.8px;margin-bottom:10px;
473
+ }
474
+ .examples-scroll{display:flex;gap:10px;overflow-x:auto;padding-bottom:8px}
475
+ .examples-scroll::-webkit-scrollbar{height:6px}
476
+ .examples-scroll::-webkit-scrollbar-track{background:#09090b;border-radius:3px}
477
+ .examples-scroll::-webkit-scrollbar-thumb{background:#292524;border-radius:3px}
478
+ .examples-scroll::-webkit-scrollbar-thumb:hover{background:#44403c}
479
+ .example-card{
480
+ flex-shrink:0;width:220px;background:#09090b;border:1px solid #292524;
481
+ border-radius:10px;overflow:hidden;cursor:pointer;transition:all .2s ease;
482
+ }
483
+ .example-card:hover{border-color:#FF4500;transform:translateY(-2px);box-shadow:0 4px 12px rgba(255,69,0,.12)}
484
+ .example-card.loading{opacity:.5;pointer-events:none}
485
+ .example-thumbs{display:flex;height:120px;overflow:hidden;background:#18181b}
486
+ .example-thumbs img{width:100%;height:100%;object-fit:cover;border-bottom:1px solid #292524}
487
+ .example-thumb-placeholder{
488
+ flex:1;display:flex;align-items:center;justify-content:center;
489
+ background:#18181b;color:#57534e;font-size:11px;min-width:0;
490
+ }
491
+ .example-meta{padding:6px 10px;display:flex;align-items:center;gap:6px}
492
+ .example-badge{
493
+ display:inline-flex;padding:2px 7px;background:rgba(255,69,0,.1);border-radius:4px;
494
+ font-size:10px;font-weight:700;color:#ff8a65;font-family:'JetBrains Mono',monospace;white-space:nowrap;
495
+ }
496
+ .example-prompt-text{
497
+ padding:0 10px 8px;font-size:11px;color:#d6d3d1;line-height:1.4;
498
+ display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;
499
+ }
500
+
501
+ .panel-card{border-bottom:1px solid #292524}
502
+ .panel-card-title{
503
+ padding:12px 20px;font-size:12px;font-weight:700;color:#a8a29e;
504
+ text-transform:uppercase;letter-spacing:.8px;border-bottom:1px solid rgba(41,37,36,.7);
505
+ }
506
+ .panel-card-body{padding:16px 20px;display:flex;flex-direction:column;gap:8px}
507
+ .modern-label{font-size:13px;font-weight:600;color:#d6d3d1;margin-bottom:4px;display:block}
508
+ .modern-textarea{
509
+ width:100%;background:#09090b;border:1px solid #292524;border-radius:10px;
510
+ padding:11px 14px;font-family:'Inter',sans-serif;font-size:14px;color:#f5f5f4;
511
+ resize:none;outline:none;min-height:90px;transition:border-color .2s, box-shadow .2s;
512
+ }
513
+ .modern-textarea:focus{border-color:#FF4500;box-shadow:0 0 0 3px rgba(255,69,0,.14)}
514
+ .modern-textarea::placeholder{color:#78716c}
515
+ .modern-textarea.error-flash{
516
+ border-color:#ef4444!important;box-shadow:0 0 0 3px rgba(239,68,68,.2)!important;animation:shake .4s ease;
517
+ }
518
+ @keyframes shake{0%,100%{transform:translateX(0)}20%,60%{transform:translateX(-4px)}40%,80%{transform:translateX(4px)}}
519
+
520
+ .toast-notification{
521
+ position:fixed;top:24px;left:50%;transform:translateX(-50%) translateY(-120%);
522
+ z-index:9999;padding:10px 24px;border-radius:10px;font-family:'Inter',sans-serif;
523
+ font-size:14px;font-weight:600;display:flex;align-items:center;gap:8px;
524
+ box-shadow:0 8px 24px rgba(0,0,0,.5);
525
+ transition:transform .35s cubic-bezier(.34,1.56,.64,1),opacity .35s ease;opacity:0;pointer-events:none;
526
+ }
527
+ .toast-notification.visible{transform:translateX(-50%) translateY(0);opacity:1;pointer-events:auto}
528
+ .toast-notification.error{background:linear-gradient(135deg,#dc2626,#b91c1c);color:#fff;border:1px solid rgba(255,255,255,.15)}
529
+ .toast-notification.warning{background:linear-gradient(135deg,#ea580c,#c2410c);color:#fff;border:1px solid rgba(255,255,255,.15)}
530
+ .toast-notification.info{background:linear-gradient(135deg,#f97316,#ea580c);color:#fff;border:1px solid rgba(255,255,255,.15)}
531
+ .toast-notification .toast-icon{font-size:16px;line-height:1}
532
+ .toast-notification .toast-text{line-height:1.3}
533
+
534
+ .btn-run{
535
+ display:flex;align-items:center;justify-content:center;gap:8px;width:100%;
536
+ background:linear-gradient(135deg,#FF6A3D,#FF4500);border:none;border-radius:12px;
537
+ padding:12px 24px;cursor:pointer;font-size:15px;font-weight:700;font-family:'Inter',sans-serif;
538
+ color:#fff!important;transition:all .2s ease;letter-spacing:-.2px;
539
+ box-shadow:0 4px 16px rgba(255,69,0,.28),inset 0 1px 0 rgba(255,255,255,.1);
540
+ }
541
+ .btn-run:hover{
542
+ background:linear-gradient(135deg,#ff7f50,#FF4500);transform:translateY(-1px);
543
+ box-shadow:0 6px 24px rgba(255,69,0,.4),inset 0 1px 0 rgba(255,255,255,.15);
544
+ }
545
+ .btn-run:active{transform:translateY(0);box-shadow:0 2px 8px rgba(255,69,0,.28)}
546
+ .btn-run svg{width:18px;height:18px}
547
+ .btn-run svg *{fill:#fff!important;stroke:#fff!important}
548
+
549
+ .output-frame{border-bottom:1px solid #292524;display:flex;flex-direction:column;position:relative}
550
+ .output-frame .out-title{
551
+ padding:10px 20px;font-size:13px;font-weight:800;color:#fff!important;
552
+ text-transform:uppercase;letter-spacing:.8px;
553
+ border-bottom:1px solid rgba(41,37,36,.7);display:flex;align-items:center;justify-content:space-between;
554
+ }
555
+ .output-frame .out-body{
556
+ flex:1;background:#09090b;display:flex;align-items:stretch;justify-content:stretch;
557
+ overflow:hidden;min-height:330px;max-height:330px;position:relative;
558
+ }
559
+ .output-html-wrap{
560
+ width:100%;height:100%;padding:14px;
561
+ }
562
+ .output-scroll{
563
+ width:100%;height:100%;
564
+ background:#0c0c0f;border:1px solid #292524;border-radius:10px;
565
+ padding:12px 14px;color:#f5f5f4;
566
+ font-family:'JetBrains Mono',monospace;font-size:13px;line-height:1.55;
567
+ white-space:pre-wrap;word-break:break-word;overflow:auto;
568
+ }
569
+ .output-scroll.placeholder{display:flex;align-items:center;justify-content:center;color:#78716c;font-family:'Inter',sans-serif}
570
+ .output-scroll::-webkit-scrollbar{width:8px;height:8px}
571
+ .output-scroll::-webkit-scrollbar-track{background:#111113}
572
+ .output-scroll::-webkit-scrollbar-thumb{background:#292524;border-radius:4px}
573
+ .output-scroll::-webkit-scrollbar-thumb:hover{background:#44403c}
574
+
575
+ .modern-loader{
576
+ display:none;position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(9,9,11,.92);
577
+ z-index:15;flex-direction:column;align-items:center;justify-content:center;gap:16px;backdrop-filter:blur(4px);
578
+ }
579
+ .modern-loader.active{display:flex}
580
+ .modern-loader .loader-spinner{
581
+ width:36px;height:36px;border:3px solid #292524;border-top-color:#FF4500;
582
+ border-radius:50%;animation:spin .8s linear infinite;
583
+ }
584
+ @keyframes spin{to{transform:rotate(360deg)}}
585
+ .modern-loader .loader-text{font-size:13px;color:#d6d3d1;font-weight:600}
586
+ .loader-bar-track{width:200px;height:4px;background:#292524;border-radius:2px;overflow:hidden}
587
+ .loader-bar-fill{
588
+ height:100%;background:linear-gradient(90deg,#FF4500,#FF7A4D,#FF4500);
589
+ background-size:200% 100%;animation:shimmer 1.5s ease-in-out infinite;border-radius:2px;
590
+ }
591
+ @keyframes shimmer{0%{background-position:200% 0}100%{background-position:-200% 0}}
592
+
593
+ .settings-group{border:1px solid #292524;border-radius:12px;margin:12px 16px;padding:0;overflow:hidden}
594
+ .settings-group-title{
595
+ font-size:12px;font-weight:700;color:#a8a29e;text-transform:uppercase;letter-spacing:.8px;
596
+ padding:10px 16px;border-bottom:1px solid #292524;background:rgba(24,24,27,.5);
597
+ }
598
+ .settings-group-body{padding:14px 16px;display:flex;flex-direction:column;gap:12px}
599
+ .slider-row{display:flex;align-items:center;gap:10px;min-height:28px}
600
+ .slider-row label{font-size:13px;font-weight:600;color:#d6d3d1;min-width:106px;flex-shrink:0}
601
+ .slider-row input[type="range"]{
602
+ flex:1;-webkit-appearance:none;appearance:none;height:6px;background:#292524;
603
+ border-radius:3px;outline:none;min-width:0;
604
+ }
605
+ .slider-row input[type="range"]::-webkit-slider-thumb{
606
+ -webkit-appearance:none;width:16px;height:16px;background:linear-gradient(135deg,#FF6A3D,#FF4500);
607
+ border-radius:50%;cursor:pointer;box-shadow:0 2px 6px rgba(255,69,0,.35);transition:transform .15s;
608
+ }
609
+ .slider-row input[type="range"]::-webkit-slider-thumb:hover{transform:scale(1.2)}
610
+ .slider-row input[type="range"]::-moz-range-thumb{
611
+ width:16px;height:16px;background:linear-gradient(135deg,#FF6A3D,#FF4500);
612
+ border-radius:50%;cursor:pointer;border:none;box-shadow:0 2px 6px rgba(255,69,0,.35);
613
+ }
614
+ .slider-row .slider-val{
615
+ min-width:66px;text-align:right;font-family:'JetBrains Mono',monospace;font-size:12px;
616
+ font-weight:600;padding:3px 8px;background:#09090b;border:1px solid #292524;
617
+ border-radius:6px;color:#f5f5f4;flex-shrink:0;
618
+ }
619
+
620
+ .segmented-wrap{
621
+ display:flex;gap:8px;flex-wrap:wrap;
622
+ }
623
+ .segmented-btn{
624
+ display:inline-flex;align-items:center;justify-content:center;
625
+ padding:7px 12px;border-radius:999px;border:1px solid #44403c;background:#09090b;
626
+ color:#d6d3d1;font-size:12px;font-weight:700;font-family:'JetBrains Mono',monospace;
627
+ cursor:pointer;transition:all .15s ease;
628
+ }
629
+ .segmented-btn:hover{border-color:#FF4500;background:rgba(255,69,0,.06)}
630
+ .segmented-btn.active{
631
+ background:linear-gradient(135deg,#FF6A3D,#FF4500);
632
+ color:#fff;border-color:#FF4500;box-shadow:0 2px 10px rgba(255,69,0,.25);
633
+ }
634
+
635
+ .model-list{
636
+ display:flex;flex-wrap:wrap;gap:8px;
637
+ }
638
+ .model-chip{
639
+ display:inline-flex;align-items:center;justify-content:center;
640
+ padding:8px 12px;border-radius:999px;border:1px solid #44403c;background:#09090b;
641
+ color:#d6d3d1;font-size:12px;font-weight:700;cursor:pointer;transition:all .15s ease;
642
+ }
643
+ .model-chip:hover{border-color:#FF4500;background:rgba(255,69,0,.06);transform:translateY(-1px)}
644
+ .model-chip.active{
645
+ background:linear-gradient(135deg,#FF6A3D,#FF4500);
646
+ color:#fff;border-color:#FF4500;box-shadow:0 2px 10px rgba(255,69,0,.25);
647
+ }
648
+
649
+ .app-statusbar{
650
+ background:#18181b;border-top:1px solid #292524;padding:6px 20px;
651
+ display:flex;gap:12px;height:34px;align-items:center;font-size:12px;
652
+ }
653
+ .app-statusbar .sb-section{
654
+ padding:0 12px;flex:1;display:flex;align-items:center;font-family:'JetBrains Mono',monospace;
655
+ font-size:12px;color:#a8a29e;overflow:hidden;white-space:nowrap;
656
+ }
657
+ .app-statusbar .sb-section.sb-fixed{
658
+ flex:0 0 auto;min-width:120px;text-align:center;justify-content:center;
659
+ padding:3px 12px;background:rgba(255,69,0,.08);border-radius:6px;color:#ff8a65;font-weight:700;
660
+ }
661
+
662
+ .exp-note{padding:10px 20px;font-size:12px;color:#78716c;border-top:1px solid #292524;text-align:center}
663
+ .exp-note a{color:#ff8a65;text-decoration:none}
664
+ .exp-note a:hover{text-decoration:underline}
665
+
666
+ @media(max-width:940px){
667
+ .app-main-row{flex-direction:column}
668
+ .app-main-right{width:100%}
669
+ .app-main-left{border-right:none;border-bottom:1px solid #292524}
670
+ }
671
  """
672
 
673
+ UPLOAD_SVG = '<svg class="tb-svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>'
674
+ CLEAR_SVG = '<svg class="tb-svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>'
675
+ OCR_RUN_SVG = '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12 5c-5.6 0-9.5 5-9.5 7s3.9 7 9.5 7 9.5-5 9.5-7-3.9-7-9.5-7zm0 11a4 4 0 1 1 0-8 4 4 0 0 1 0 8z"/><circle cx="12" cy="12" r="1.8"/></svg>'
676
+
677
  gallery_js = r"""
678
  () => {
679
  function init() {
680
+ if (window.__ocrAppInitDone) return;
681
 
682
+ const dropZone = document.getElementById('image-drop-zone');
683
+ const uploadPrompt = document.getElementById('upload-prompt');
684
  const uploadClick = document.getElementById('upload-click-area');
685
+ const fileInput = document.getElementById('custom-file-input');
686
  const previewWrap = document.getElementById('image-preview-wrap');
687
+ const previewImg = document.getElementById('preview-img');
688
+ const removeBtn = document.getElementById('image-remove-btn');
689
+ const btnUpload = document.getElementById('tb-upload');
690
+ const btnClear = document.getElementById('tb-clear');
691
  const queryInput = document.getElementById('custom-query-input');
692
+ const runBtnEl = document.getElementById('custom-run-btn');
693
+ const imgStatus = document.getElementById('tb-image-status');
694
+ const sbImage = document.getElementById('sb-image-status');
695
 
696
+ if (!dropZone || !fileInput || !queryInput) {
697
  setTimeout(init, 250);
698
  return;
699
  }
700
 
701
+ window.__ocrAppInitDone = true;
702
+
703
+ let currentImage = null;
704
  let toastTimer = null;
705
 
706
  function showToast(message, type) {
 
709
  toast = document.createElement('div');
710
  toast.id = 'app-toast';
711
  toast.className = 'toast-notification';
712
+ toast.innerHTML = '<span class="toast-icon"></span><span class="toast-text"></span>';
713
  document.body.appendChild(toast);
714
  }
715
+ const icon = toast.querySelector('.toast-icon');
716
+ const text = toast.querySelector('.toast-text');
717
  toast.className = 'toast-notification ' + (type || 'error');
718
+ if (type === 'warning') icon.textContent = '\u26A0';
719
+ else if (type === 'info') icon.textContent = '\u2139';
720
+ else icon.textContent = '\u2717';
721
+ text.textContent = message;
722
  if (toastTimer) clearTimeout(toastTimer);
723
  void toast.offsetWidth;
724
  toast.classList.add('visible');
725
+ toastTimer = setTimeout(() => toast.classList.remove('visible'), 3500);
726
  }
727
  window.__showToast = showToast;
728
 
729
+ function flashQueryError() {
730
+ queryInput.classList.add('error-flash');
731
+ queryInput.focus();
732
+ setTimeout(() => queryInput.classList.remove('error-flash'), 800);
 
733
  }
734
 
735
  function setGradioValue(containerId, value) {
 
748
  }
749
  window.__setGradioValue = setGradioValue;
750
 
751
+ function updateImageUI() {
752
+ const hasImage = !!(currentImage && currentImage.b64);
753
+ if (hasImage) {
754
+ uploadPrompt.style.display = 'none';
755
+ previewWrap.classList.add('visible');
756
+ previewImg.src = currentImage.b64;
757
+ if (imgStatus) imgStatus.textContent = '1 image loaded';
758
+ if (sbImage) sbImage.textContent = currentImage.name ? currentImage.name : '1 image uploaded';
759
+ } else {
760
+ uploadPrompt.style.display = '';
761
+ previewWrap.classList.remove('visible');
762
+ previewImg.removeAttribute('src');
763
+ if (imgStatus) imgStatus.textContent = 'No image';
764
+ if (sbImage) sbImage.textContent = 'No image uploaded';
765
+ }
766
  }
767
 
768
+ function syncImageToGradio() {
769
+ setGradioValue('hidden-image-b64', currentImage && currentImage.b64 ? currentImage.b64 : '');
 
 
770
  }
771
 
772
+ function syncQueryToGradio() {
773
+ setGradioValue('query-gradio-input', queryInput.value || '');
 
 
 
 
 
 
 
 
 
 
 
 
774
  }
775
 
776
+ function addImage(b64, name) {
777
+ currentImage = { b64, name: name || 'image' };
778
+ updateImageUI();
779
+ syncImageToGradio();
780
  }
781
+ window.__addOCRImage = addImage;
782
 
783
  function clearImage() {
784
+ currentImage = null;
785
+ updateImageUI();
786
+ syncImageToGradio();
787
  }
788
+ window.__clearOCRImage = clearImage;
789
 
790
+ function processFiles(files) {
791
+ const file = Array.from(files || []).find(f => f.type && f.type.startsWith('image/'));
792
+ if (!file) {
793
+ showToast('Please upload a valid image file', 'error');
794
  return;
795
  }
796
  const reader = new FileReader();
797
+ reader.onload = (e) => addImage(e.target.result, file.name);
798
  reader.readAsDataURL(file);
799
  }
800
 
801
+ fileInput.addEventListener('change', (e) => { processFiles(e.target.files); e.target.value = ''; });
802
+ uploadClick.addEventListener('click', () => fileInput.click());
803
+ if (btnUpload) btnUpload.addEventListener('click', () => fileInput.click());
804
+ if (btnClear) btnClear.addEventListener('click', clearImage);
805
+ if (removeBtn) removeBtn.addEventListener('click', clearImage);
806
 
807
+ dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('drag-over'); });
808
+ dropZone.addEventListener('dragleave', (e) => { e.preventDefault(); dropZone.classList.remove('drag-over'); });
809
+ dropZone.addEventListener('drop', (e) => {
 
 
 
 
 
 
810
  e.preventDefault();
811
+ dropZone.classList.remove('drag-over');
812
+ if (e.dataTransfer.files.length) processFiles(e.dataTransfer.files);
813
  });
814
+
815
+ queryInput.addEventListener('input', syncQueryToGradio);
816
+
817
+ window.__setOCRPrompt = function(text) {
818
+ queryInput.value = text || '';
819
+ syncQueryToGradio();
820
+ };
821
+
822
+ function setActiveModel(value) {
823
+ document.querySelectorAll('.model-chip').forEach(chip => {
824
+ chip.classList.toggle('active', chip.getAttribute('data-value') === value);
825
+ });
826
+ setGradioValue('model-choice-hidden', value);
827
+ }
828
+
829
+ document.querySelectorAll('.model-chip').forEach(chip => {
830
+ chip.addEventListener('click', () => setActiveModel(chip.getAttribute('data-value')));
831
  });
832
 
833
+ function setActiveGpu(value) {
834
+ document.querySelectorAll('.segmented-btn').forEach(btn => {
835
+ btn.classList.toggle('active', btn.getAttribute('data-value') === value);
836
+ });
837
+ setGradioValue('gpu-duration-input', value);
838
+ }
839
+
840
+ document.querySelectorAll('.segmented-btn').forEach(btn => {
841
+ btn.addEventListener('click', () => setActiveGpu(btn.getAttribute('data-value')));
842
+ });
843
 
844
  function syncSlider(customId, gradioId) {
845
  const slider = document.getElementById(customId);
 
866
  syncSlider('custom-top-k', 'gradio-top-k');
867
  syncSlider('custom-repetition-penalty', 'gradio-repetition-penalty');
868
 
869
+ function showLoader() {
870
+ const l = document.getElementById('output-loader');
871
+ if (l) l.classList.add('active');
872
+ const sb = document.querySelector('.sb-fixed');
873
+ if (sb) sb.textContent = 'Processing...';
 
 
874
  }
 
875
 
876
+ function hideLoader() {
877
+ const l = document.getElementById('output-loader');
878
+ if (l) l.classList.remove('active');
879
+ const sb = document.querySelector('.sb-fixed');
880
+ if (sb) sb.textContent = 'Done';
881
+ }
882
+
883
+ window.__showLoader = showLoader;
884
+ window.__hideLoader = hideLoader;
885
 
886
  function validateBeforeRun() {
887
+ const hasImage = !!(currentImage && currentImage.b64);
888
+ const queryVal = (queryInput.value || '').trim();
889
+
890
+ if (!hasImage && !queryVal) {
891
+ showToast('Please upload an image and enter a query', 'error');
892
+ flashQueryError();
893
  return false;
894
  }
895
+ if (!hasImage) {
896
+ showToast('Please upload an image', 'error');
 
897
  return false;
898
  }
899
+ if (!queryVal) {
900
+ showToast('Please enter a query', 'warning');
901
+ flashQueryError();
902
  return false;
903
  }
 
 
904
 
905
+ if (queryVal.length > 4000) {
906
+ showToast('Query is too long', 'warning');
907
+ flashQueryError();
908
+ return false;
909
+ }
910
+
911
+ return true;
 
 
 
 
912
  }
 
 
913
 
914
+ window.__clickGradioRunBtn = function() {
915
+ if (!validateBeforeRun()) return;
916
+ syncQueryToGradio();
917
+ syncImageToGradio();
918
+ showLoader();
919
+ setTimeout(() => {
920
+ const gradioBtn = document.getElementById('gradio-run-btn');
921
+ if (!gradioBtn) return;
922
+ const btn = gradioBtn.querySelector('button');
923
+ if (btn) btn.click(); else gradioBtn.click();
924
+ }, 200);
925
  };
926
 
927
+ if (runBtnEl) runBtnEl.addEventListener('click', () => window.__clickGradioRunBtn());
928
+
929
  document.querySelectorAll('.example-card[data-idx]').forEach(card => {
930
  card.addEventListener('click', () => {
931
  const idx = card.getAttribute('data-idx');
 
934
  showToast('Loading example...', 'info');
935
  setGradioValue('example-result-data', '');
936
  setGradioValue('example-idx-input', idx);
 
937
  setTimeout(() => {
938
  const btn = document.getElementById('example-load-btn');
939
  if (btn) {
940
+ const b = btn.querySelector('button');
941
+ if (b) b.click(); else btn.click();
942
  }
943
+ }, 120);
944
+ setTimeout(() => card.classList.remove('loading'), 8000);
 
945
  });
946
  });
947
 
948
+ setActiveModel('FireRed-OCR');
949
+ setActiveGpu('60');
950
+ updateImageUI();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
951
  }
952
  init();
953
  }
 
955
 
956
  wire_outputs_js = r"""
957
  () => {
958
+ function watchOutput() {
959
+ const resultContainer = document.getElementById('gradio-raw-output');
960
+ const outBox = document.getElementById('raw-output-box');
961
+ if (!resultContainer || !outBox) { setTimeout(watchOutput, 400); return; }
962
+
963
+ function syncOutput() {
964
+ const textarea = resultContainer.querySelector('textarea');
965
+ const input = resultContainer.querySelector('input');
966
+ const el = textarea || input;
967
+ if (!el) return;
968
+ const val = el.value || '';
969
+ if (val && val.trim().length > 0) {
970
+ outBox.classList.remove('placeholder');
971
+ outBox.textContent = val;
972
+ outBox.scrollTop = outBox.scrollHeight;
 
 
 
 
 
 
 
 
 
 
 
973
  if (window.__hideLoader) window.__hideLoader();
974
+ } else {
975
+ outBox.classList.add('placeholder');
976
+ outBox.textContent = 'Raw OCR output will appear here';
977
  }
978
  }
979
 
980
+ const observer = new MutationObserver(syncOutput);
981
+ observer.observe(resultContainer, {childList:true, subtree:true, attributes:true, characterData:true});
982
+ setInterval(syncOutput, 700);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
983
  }
984
+ watchOutput();
985
 
986
  function watchExampleResults() {
987
  const container = document.getElementById('example-result-data');
988
+ if (!container) { setTimeout(watchExampleResults, 500); return; }
 
 
 
989
 
990
  let lastProcessed = '';
991
 
992
+ function checkResult() {
993
+ const el = container.querySelector('textarea') || container.querySelector('input');
994
  if (!el) return;
995
  const val = el.value;
996
  if (!val || val === lastProcessed || val.length < 10) return;
997
 
998
  try {
999
  const data = JSON.parse(val);
1000
+ if (data.status === 'ok' && data.image) {
1001
  lastProcessed = val;
1002
+ if (window.__clearOCRImage) window.__clearOCRImage();
1003
+ if (window.__setOCRPrompt && data.query) window.__setOCRPrompt(data.query);
1004
+ if (window.__addOCRImage) window.__addOCRImage(data.image, 'example.jpg');
1005
  document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));
1006
+ if (window.__showToast) window.__showToast('Example loaded', 'info');
1007
+ } else if (data.status === 'error') {
1008
  document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));
1009
+ if (window.__showToast) window.__showToast('Could not load example', 'error');
1010
  }
1011
+ } catch(e) {
1012
  console.error('Example parse error:', e);
1013
  }
1014
  }
1015
 
1016
+ const obs = new MutationObserver(checkResult);
1017
  obs.observe(container, {childList:true, subtree:true, characterData:true, attributes:true});
1018
+ setInterval(checkResult, 500);
1019
  }
1020
  watchExampleResults();
1021
+
1022
+ function watchSliderBackSync() {
1023
+ const pairs = [
1024
+ ['gradio-max-new-tokens', 'custom-max-new-tokens', 'custom-max-new-tokens-val'],
1025
+ ['gradio-temperature', 'custom-temperature', 'custom-temperature-val'],
1026
+ ['gradio-top-p', 'custom-top-p', 'custom-top-p-val'],
1027
+ ['gradio-top-k', 'custom-top-k', 'custom-top-k-val'],
1028
+ ['gradio-repetition-penalty', 'custom-repetition-penalty', 'custom-repetition-penalty-val']
1029
+ ];
1030
+
1031
+ function syncOne(gradioId, customId, valId) {
1032
+ const src = document.getElementById(gradioId);
1033
+ const dst = document.getElementById(customId);
1034
+ const v = document.getElementById(valId);
1035
+ if (!src || !dst) return;
1036
+ const el = src.querySelector('input[type="range"],input[type="number"]');
1037
+ if (el && typeof el.value !== 'undefined') {
1038
+ dst.value = el.value;
1039
+ if (v) v.textContent = el.value;
1040
+ }
1041
+ }
1042
+
1043
+ setInterval(() => {
1044
+ pairs.forEach(p => syncOne(p[0], p[1], p[2]));
1045
+ }, 1200);
1046
+ }
1047
+ watchSliderBackSync();
1048
  }
1049
  """
1050
 
1051
+
1052
+ def decode_b64_to_pil(b64_str):
1053
+ if not b64_str:
1054
+ return None
1055
+ try:
1056
+ if b64_str.startswith("data:image"):
1057
+ _, data = b64_str.split(",", 1)
1058
+ else:
1059
+ data = b64_str
1060
+ image_data = base64.b64decode(data)
1061
+ return Image.open(BytesIO(image_data)).convert("RGB")
1062
+ except Exception as e:
1063
+ raise gr.Error(f"Invalid image data: {e}")
1064
+
1065
+
1066
+ @spaces.GPU
1067
+ def run_infer(model_name, query, image_b64, max_new_tokens, temperature, top_p, top_k, repetition_penalty, gpu_duration):
1068
+ image = decode_b64_to_pil(image_b64)
1069
+
1070
+ if image is None:
1071
+ raise gr.Error("Please upload an image.")
1072
+ if not query or not str(query).strip():
1073
+ raise gr.Error("Please enter a query.")
1074
+ if model_name not in ["FireRed-OCR", "Nanonets-OCR-s", "MonkeyOCR-Recognition", "Thyme-RL", "Typhoon-OCR-7B", "SmolDocling-256M-preview"]:
1075
+ raise gr.Error("Please select a valid model.")
1076
+
1077
+ stream = generate_image(
1078
+ model_name=model_name,
1079
+ text=str(query).strip(),
1080
+ image=image,
1081
+ max_new_tokens=int(max_new_tokens),
1082
+ temperature=float(temperature),
1083
+ top_p=float(top_p),
1084
+ top_k=int(top_k),
1085
+ repetition_penalty=float(repetition_penalty),
1086
+ gpu_timeout=int(gpu_duration),
1087
+ )
1088
+
1089
+ last = ""
1090
+ for chunk in stream:
1091
+ last = chunk
1092
+ yield last
1093
+
1094
+
1095
  with gr.Blocks() as demo:
1096
  hidden_image_b64 = gr.Textbox(value="", elem_id="hidden-image-b64", elem_classes="hidden-input", container=False)
1097
+ query = gr.Textbox(value="", elem_id="query-gradio-input", elem_classes="hidden-input", container=False)
1098
+ model_choice = gr.Textbox(value="FireRed-OCR", elem_id="model-choice-hidden", elem_classes="hidden-input", container=False)
1099
+ gpu_duration_input = gr.Textbox(value="60", elem_id="gpu-duration-input", elem_classes="hidden-input", container=False)
1100
 
1101
  max_new_tokens = gr.Slider(minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS, elem_id="gradio-max-new-tokens", elem_classes="hidden-input", container=False)
1102
  temperature = gr.Slider(minimum=0.1, maximum=4.0, step=0.1, value=0.6, elem_id="gradio-temperature", elem_classes="hidden-input", container=False)
 
1104
  top_k = gr.Slider(minimum=1, maximum=1000, step=1, value=50, elem_id="gradio-top-k", elem_classes="hidden-input", container=False)
1105
  repetition_penalty = gr.Slider(minimum=1.0, maximum=2.0, step=0.05, value=1.2, elem_id="gradio-repetition-penalty", elem_classes="hidden-input", container=False)
1106
 
1107
+ raw_output_hidden = gr.Textbox(value="", lines=10, elem_id="gradio-raw-output", elem_classes="hidden-input", container=False)
 
1108
 
1109
  example_idx = gr.Textbox(value="", elem_id="example-idx-input", elem_classes="hidden-input", container=False)
1110
  example_result = gr.Textbox(value="", elem_id="example-result-data", elem_classes="hidden-input", container=False)
1111
  example_load_btn = gr.Button("Load Example", elem_id="example-load-btn")
1112
 
 
 
1113
  gr.HTML(f"""
1114
  <div class="app-shell">
1115
  <div class="app-header">
1116
  <div class="app-header-left">
1117
+ <div class="app-logo">{VISION_OCR_LOGO}</div>
1118
+ <span class="app-title">Multimodal OCR 2</span>
1119
+ <span class="app-badge">Vision Based</span>
1120
+ <span class="app-badge fast">OCR Suite</span>
1121
  </div>
1122
  </div>
1123
 
1124
+ <div class="app-toolbar">
1125
+ <button id="tb-upload" class="modern-tb-btn" title="Upload image">
1126
+ {UPLOAD_SVG}<span class="tb-label">Upload</span>
1127
+ </button>
1128
+ <button id="tb-clear" class="modern-tb-btn" title="Clear image">
1129
+ {CLEAR_SVG}<span class="tb-label">Clear</span>
1130
+ </button>
1131
+ <div class="tb-sep"></div>
1132
+ <span id="tb-image-status" class="tb-info">No image</span>
1133
+ </div>
1134
 
1135
+ <div class="app-main-row">
1136
+ <div class="app-main-left">
1137
+ <div id="image-drop-zone">
1138
+ <div id="upload-prompt" class="upload-prompt-modern">
1139
+ <div id="upload-click-area" class="upload-click-area">
1140
+ <svg viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
1141
+ <rect x="8" y="14" width="64" height="52" rx="8" fill="none" stroke="#FF4500" stroke-width="2" stroke-dasharray="4 3"/>
1142
+ <path d="M18 52L31 38L42 46L55 30L66 52" fill="rgba(255,69,0,0.15)" stroke="#FF4500" stroke-width="1.5"/>
1143
+ <circle cx="29" cy="28" r="5.5" fill="rgba(255,69,0,0.2)" stroke="#FF4500" stroke-width="1.5"/>
1144
+ </svg>
1145
+ <span class="upload-main-text">Click or drag an image here</span>
1146
+ <span class="upload-sub-text">Upload one image for OCR, document parsing, or visual text extraction across multiple OCR models</span>
 
 
 
 
 
1147
  </div>
1148
  </div>
1149
+
 
 
 
1150
  <input id="custom-file-input" type="file" accept="image/*" style="display:none;" />
1151
+
1152
+ <div id="image-preview-wrap" class="image-preview-wrap">
1153
+ <div class="image-preview-card">
1154
+ <button id="image-remove-btn" class="image-remove-btn" title="Remove image">✕</button>
1155
+ <img id="preview-img" alt="Preview">
1156
+ </div>
1157
+ </div>
1158
+ </div>
1159
+
1160
+ <div class="hint-bar">
1161
+ <b>Upload:</b> Click or drag an image &nbsp;&middot;&nbsp;
1162
+ <b>Query:</b> Describe the OCR task you want &nbsp;&middot;&nbsp;
1163
+ <kbd>Clear</kbd> removes the image
1164
  </div>
1165
 
1166
  <div class="examples-section">
 
1171
  </div>
1172
  </div>
1173
 
1174
+ <div class="app-main-right">
1175
+ <div class="panel-card">
1176
+ <div class="panel-card-title">OCR Instruction</div>
1177
+ <div class="panel-card-body">
1178
+ <label class="modern-label" for="custom-query-input">Query</label>
1179
+ <textarea id="custom-query-input" class="modern-textarea" rows="4" placeholder="e.g., Perform OCR on the image precisely."></textarea>
1180
+ </div>
1181
+ </div>
1182
+
1183
+ <div class="panel-card">
1184
+ <div class="panel-card-title">Select Model</div>
1185
+ <div class="panel-card-body">
1186
+ <div class="model-list">
1187
+ <button class="model-chip active" data-value="FireRed-OCR">FireRed-OCR</button>
1188
+ <button class="model-chip" data-value="Nanonets-OCR-s">Nanonets-OCR-s</button>
1189
+ <button class="model-chip" data-value="MonkeyOCR-Recognition">MonkeyOCR-Recognition</button>
1190
+ <button class="model-chip" data-value="Thyme-RL">Thyme-RL</button>
1191
+ <button class="model-chip" data-value="Typhoon-OCR-7B">Typhoon-OCR-7B</button>
1192
+ <button class="model-chip" data-value="SmolDocling-256M-preview">SmolDocling-256M-preview</button>
1193
  </div>
1194
  </div>
1195
  </div>
1196
 
1197
+ <div class="panel-card">
1198
+ <div class="panel-card-title">GPU Duration</div>
1199
+ <div class="panel-card-body">
1200
+ <div class="segmented-wrap">
1201
+ <button class="segmented-btn active" data-value="60">60</button>
1202
+ <button class="segmented-btn" data-value="90">90</button>
1203
+ <button class="segmented-btn" data-value="120">120</button>
1204
+ <button class="segmented-btn" data-value="180">180</button>
1205
+ <button class="segmented-btn" data-value="240">240</button>
1206
+ <button class="segmented-btn" data-value="300">300</button>
1207
+ </div>
1208
+ <div style="font-size:12px;color:#78716c;">Higher GPU duration allows longer processing but uses more GPU quota.</div>
1209
+ </div>
1210
+ </div>
1211
+
1212
+ <div style="padding:12px 20px;">
1213
+ <button id="custom-run-btn" class="btn-run">
1214
+ {OCR_RUN_SVG}
1215
+ <span id="run-btn-label">Run OCR</span>
1216
  </button>
1217
  </div>
1218
 
1219
+ <div class="output-frame" style="flex:1">
1220
+ <div class="out-title">
1221
+ <span>Raw Output Stream</span>
 
1222
  </div>
1223
+ <div class="out-body">
1224
+ <div class="modern-loader" id="output-loader">
1225
  <div class="loader-spinner"></div>
1226
+ <div class="loader-text">Processing OCR...</div>
1227
+ <div class="loader-bar-track"><div class="loader-bar-fill"></div></div>
1228
+ </div>
1229
+ <div class="output-html-wrap">
1230
+ <div id="raw-output-box" class="output-scroll placeholder">Raw OCR output will appear here</div>
1231
  </div>
 
 
 
 
 
 
1232
  </div>
1233
  </div>
1234
 
1235
  <div class="settings-group">
1236
+ <div class="settings-group-title">Advanced Settings</div>
1237
  <div class="settings-group-body">
1238
  <div class="slider-row">
1239
+ <label>Max tokens</label>
1240
  <input type="range" id="custom-max-new-tokens" min="1" max="{MAX_MAX_NEW_TOKENS}" step="1" value="{DEFAULT_MAX_NEW_TOKENS}">
1241
  <span class="slider-val" id="custom-max-new-tokens-val">{DEFAULT_MAX_NEW_TOKENS}</span>
1242
  </div>
 
1243
  <div class="slider-row">
1244
  <label>Temperature</label>
1245
  <input type="range" id="custom-temperature" min="0.1" max="4.0" step="0.1" value="0.6">
1246
  <span class="slider-val" id="custom-temperature-val">0.6</span>
1247
  </div>
 
1248
  <div class="slider-row">
1249
  <label>Top-p</label>
1250
  <input type="range" id="custom-top-p" min="0.05" max="1.0" step="0.05" value="0.9">
1251
  <span class="slider-val" id="custom-top-p-val">0.9</span>
1252
  </div>
 
1253
  <div class="slider-row">
1254
  <label>Top-k</label>
1255
  <input type="range" id="custom-top-k" min="1" max="1000" step="1" value="50">
1256
  <span class="slider-val" id="custom-top-k-val">50</span>
1257
  </div>
 
1258
  <div class="slider-row">
1259
+ <label>Repetition</label>
1260
  <input type="range" id="custom-repetition-penalty" min="1.0" max="2.0" step="0.05" value="1.2">
1261
  <span class="slider-val" id="custom-repetition-penalty-val">1.2</span>
1262
  </div>
 
 
 
 
 
 
1263
  </div>
1264
  </div>
 
 
 
 
1265
  </div>
1266
  </div>
1267
 
1268
+ <div class="exp-note">
1269
+ Experimental Vision OCR interface &middot; App: <b>Multimodal OCR 2</b>
1270
+ </div>
1271
+
1272
+ <div class="app-statusbar">
1273
+ <div class="sb-section" id="sb-image-status">No image uploaded</div>
1274
+ <div class="sb-section sb-fixed">Ready</div>
1275
  </div>
1276
  </div>
1277
  """)
1278
 
1279
+ run_btn = gr.Button("Run", elem_id="gradio-run-btn")
 
 
 
 
 
 
 
1280
 
1281
  demo.load(fn=None, js=gallery_js)
1282
  demo.load(fn=None, js=wire_outputs_js)
1283
 
1284
+ run_btn.click(
1285
+ fn=run_infer,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1286
  inputs=[
1287
  model_choice,
1288
+ query,
1289
  hidden_image_b64,
1290
  max_new_tokens,
1291
  temperature,
1292
  top_p,
1293
  top_k,
1294
  repetition_penalty,
1295
+ gpu_duration_input,
1296
  ],
1297
+ outputs=[raw_output_hidden],
1298
+ js=r"""(m, q, img, max_t, temp, topp, topk, rep, gpu) => {
1299
+ const qEl = document.getElementById('custom-query-input');
1300
+ const queryVal = qEl ? qEl.value : q;
1301
  const imgContainer = document.getElementById('hidden-image-b64');
1302
+ let imgVal = img;
1303
  if (imgContainer) {
1304
+ const el = imgContainer.querySelector('textarea, input');
1305
+ if (el) imgVal = el.value;
1306
  }
1307
+ return [m, queryVal, imgVal, max_t, temp, topp, topk, rep, gpu];
1308
  }""",
1309
  )
1310
 
1311
+ example_load_btn.click(
1312
+ fn=load_example_data,
1313
+ inputs=[example_idx],
1314
+ outputs=[example_result],
1315
+ queue=False,
1316
+ )
1317
+
1318
  if __name__ == "__main__":
1319
  demo.queue(max_size=50).launch(
1320
  css=css,