File size: 27,058 Bytes
cfb37bf
fb3185e
 
 
bb2fbb1
 
349175e
c662fe8
2c99aea
f094617
349175e
c79571d
fb3185e
 
cfb37bf
c79571d
c662fe8
c79571d
 
 
 
 
 
490767e
 
c79571d
 
 
490767e
c662fe8
fb3185e
 
 
 
 
 
 
c79571d
 
 
fb3185e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c79571d
 
 
fb3185e
 
 
 
 
 
 
c79571d
 
 
fb3185e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c79571d
 
 
fb3185e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c79571d
 
 
fb3185e
 
 
 
 
 
 
c79571d
 
 
fb3185e
 
 
 
 
 
 
 
c79571d
bb2fbb1
2c99aea
 
 
 
 
 
bb2fbb1
2c99aea
 
 
 
 
 
 
 
bb2fbb1
2c99aea
 
 
 
 
bb2fbb1
2c99aea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb2fbb1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3185e
bb2fbb1
 
2c99aea
 
 
bb2fbb1
 
 
 
 
 
 
2c99aea
0dfe1bf
 
 
 
2c99aea
0dfe1bf
 
2c99aea
bb2fbb1
0dfe1bf
bb2fbb1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349175e
bb2fbb1
 
 
 
 
 
 
 
 
 
 
 
 
 
349175e
bb2fbb1
 
fb3185e
c79571d
349175e
 
 
 
 
 
 
 
 
 
 
bb2fbb1
c79571d
 
bb2fbb1
2c99aea
c79571d
2c99aea
349175e
 
2c99aea
 
bb2fbb1
 
2c99aea
bb2fbb1
349175e
2c99aea
 
bb2fbb1
466f0d3
0dfe1bf
349175e
 
bb2fbb1
 
 
 
 
 
2c99aea
349175e
 
 
 
 
 
bb2fbb1
 
 
 
c79571d
2c99aea
bb2fbb1
 
 
 
 
 
 
 
 
 
 
 
349175e
bb2fbb1
 
 
 
2c99aea
 
 
0dfe1bf
349175e
133333c
c79571d
349175e
bb2fbb1
c79571d
 
 
2c99aea
c79571d
0dfe1bf
349175e
 
2c99aea
 
bb2fbb1
2c99aea
 
 
349175e
2c99aea
0dfe1bf
349175e
0dfe1bf
 
349175e
 
2c99aea
bb2fbb1
 
 
 
 
 
 
 
 
349175e
 
 
 
bb2fbb1
 
 
 
c79571d
2c99aea
349175e
 
bb2fbb1
 
c662fe8
bb2fbb1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349175e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c99aea
 
 
bb2fbb1
2c99aea
 
 
 
349175e
2c99aea
 
 
 
349175e
bb2fbb1
0914acb
2c99aea
 
 
349175e
 
2c99aea
 
bb2fbb1
 
349175e
2c99aea
 
349175e
2c99aea
 
349175e
 
bb2fbb1
 
 
0914acb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb2fbb1
 
 
 
 
 
 
349175e
 
 
 
bb2fbb1
 
 
 
 
 
 
 
 
349175e
 
 
bb2fbb1
 
 
349175e
bb2fbb1
 
 
0914acb
 
 
bb2fbb1
0914acb
 
 
 
 
bb2fbb1
 
 
0914acb
 
bb2fbb1
 
 
 
 
 
 
0914acb
2c99aea
bb2fbb1
 
 
 
 
 
2c99aea
349175e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c99aea
fb3185e
2c99aea
349175e
2c99aea
 
133333c
fb3185e
 
349175e
 
 
0dfe1bf
bb2fbb1
349175e
 
 
bb2fbb1
c79571d
2c99aea
 
 
bb2fbb1
c79571d
 
 
2c99aea
c79571d
2c99aea
c79571d
bb2fbb1
 
 
 
 
 
0dfe1bf
bb2fbb1
349175e
 
0914acb
0dfe1bf
 
349175e
 
 
c662fe8
bb2fbb1
349175e
 
 
bb2fbb1
c79571d
2c99aea
 
 
bb2fbb1
c79571d
 
2c99aea
 
 
 
c79571d
 
 
2c99aea
c79571d
2c99aea
c79571d
133333c
349175e
 
 
0914acb
c6b50f6
 
349175e
 
 
c6b50f6
bb2fbb1
349175e
 
 
bb2fbb1
 
 
 
 
 
c6b50f6
349175e
 
 
0914acb
fb3185e
c6b50f6
349175e
c6b50f6
bb2fbb1
 
349175e
 
bb2fbb1
 
349175e
 
 
bb2fbb1
349175e
2c99aea
c6b50f6
 
fb3185e
 
349175e
fb3185e
 
2c99aea
 
 
 
bb2fbb1
2c99aea
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
import gradio as gr
import json
import tempfile
import os
import zipfile
import shutil
from typing import List, Optional, Literal, Union, Dict
from PIL import Image
import requests
from pathlib import Path
import spaces
from visualizer import htrflow_visualizer
from htrflow.volume.volume import Collection
from htrflow.pipeline.pipeline import Pipeline


DEFAULT_OUTPUT = "alto"
FORMAT_CHOICES = [
    "letter_english",
    "letter_swedish",
    "spread_english",
    "spread_swedish",
]
FILE_CHOICES = ["txt", "alto", "page", "json"]

FormatChoices = Literal[
    "letter_english", "letter_swedish", "spread_english", "spread_swedish"
]
FileChoices = Literal["txt", "alto", "page", "json"]

PIPELINE_CONFIGS = {
    "letter_english": {
        "steps": [
            {
                "step": "Segmentation",
                "settings": {
                    "model": "yolo",
                    "model_settings": {
                        "model": "Riksarkivet/yolov9-lines-within-regions-1"
                    },
                    "generation_settings": {"batch_size": 8},
                },
            },
            {
                "step": "TextRecognition",
                "settings": {
                    "model": "TrOCR",
                    "model_settings": {"model": "microsoft/trocr-base-handwritten"},
                    "generation_settings": {"batch_size": 16},
                },
            },
            {"step": "OrderLines"},
        ]
    },
    "letter_swedish": {
        "steps": [
            {
                "step": "Segmentation",
                "settings": {
                    "model": "yolo",
                    "model_settings": {
                        "model": "Riksarkivet/yolov9-lines-within-regions-1"
                    },
                    "generation_settings": {"batch_size": 8},
                },
            },
            {
                "step": "TextRecognition",
                "settings": {
                    "model": "TrOCR",
                    "model_settings": {
                        "model": "Riksarkivet/trocr-base-handwritten-hist-swe-2"
                    },
                    "generation_settings": {"batch_size": 16},
                },
            },
            {"step": "OrderLines"},
        ]
    },
    "spread_english": {
        "steps": [
            {
                "step": "Segmentation",
                "settings": {
                    "model": "yolo",
                    "model_settings": {"model": "Riksarkivet/yolov9-regions-1"},
                    "generation_settings": {"batch_size": 4},
                },
            },
            {
                "step": "Segmentation",
                "settings": {
                    "model": "yolo",
                    "model_settings": {
                        "model": "Riksarkivet/yolov9-lines-within-regions-1"
                    },
                    "generation_settings": {"batch_size": 8},
                },
            },
            {
                "step": "TextRecognition",
                "settings": {
                    "model": "TrOCR",
                    "model_settings": {"model": "microsoft/trocr-base-handwritten"},
                    "generation_settings": {"batch_size": 16},
                },
            },
            {"step": "ReadingOrderMarginalia", "settings": {"two_page": True}},
        ]
    },
    "spread_swedish": {
        "steps": [
            {
                "step": "Segmentation",
                "settings": {
                    "model": "yolo",
                    "model_settings": {"model": "Riksarkivet/yolov9-regions-1"},
                    "generation_settings": {"batch_size": 4},
                },
            },
            {
                "step": "Segmentation",
                "settings": {
                    "model": "yolo",
                    "model_settings": {
                        "model": "Riksarkivet/yolov9-lines-within-regions-1"
                    },
                    "generation_settings": {"batch_size": 8},
                },
            },
            {
                "step": "TextRecognition",
                "settings": {
                    "model": "TrOCR",
                    "model_settings": {
                        "model": "Riksarkivet/trocr-base-handwritten-hist-swe-2"
                    },
                    "generation_settings": {"batch_size": 16},
                },
            },
            {"step": "ReadingOrderMarginalia", "settings": {"two_page": True}},
        ]
    },
}


def handle_image_input(image_path: Union[str, None], progress: gr.Progress = None, desc_prefix: str = "") -> str:
    """
    Handle image input from various sources (local file, URL, or uploaded file).
    
    Args:
        image_path: Path to image file or URL
        progress: Progress tracker for UI updates
        desc_prefix: Prefix for progress descriptions
        
    Returns:
        Local file path to the image
    """
    if not image_path:
        raise ValueError("No image provided. Please upload an image or provide a URL.")
    
    if progress:
        progress(0.1, desc=f"{desc_prefix}Processing image input...")
    
    # If it's a URL, download the image
    if isinstance(image_path, str) and (image_path.startswith("http://") or image_path.startswith("https://")):
        try:
            if progress:
                progress(0.2, desc=f"{desc_prefix}Downloading image from URL...")
            response = requests.get(image_path, timeout=30)
            response.raise_for_status()
            
            # Save to temporary file
            with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp_file:
                tmp_file.write(response.content)
                image_path = tmp_file.name
                
            # Verify it's a valid image
            try:
                img = Image.open(image_path)
                img.verify()
            except Exception as e:
                os.unlink(image_path)
                raise ValueError(f"Downloaded file is not a valid image: {str(e)}")
                
        except requests.RequestException as e:
            raise ValueError(f"Failed to download image from URL: {str(e)}")
    
    # Verify the file exists
    if not os.path.exists(image_path):
        raise ValueError(f"Image file not found: {image_path}")
    
    return image_path


def parse_image_input(image_input: Union[str, List[str], None]) -> List[str]:
    """
    Parse image input which can be a single path, multiple paths, or URLs separated by newlines.
    
    Args:
        image_input: Single image path, list of paths, or newline-separated URLs/paths
        
    Returns:
        List of image paths/URLs
    """
    if not image_input:
        return []
    
    if isinstance(image_input, list):
        return image_input
    
    if isinstance(image_input, str):
        # Check if it's multiple URLs/paths separated by newlines
        lines = image_input.strip().split('\n')
        paths = []
        for line in lines:
            line = line.strip()
            if line:  # Skip empty lines
                paths.append(line)
        return paths if paths else [image_input]
    
    return []


@spaces.GPU
def _process_htr_pipeline_batch(
    image_paths: List[str], 
    document_type: FormatChoices, 
    custom_settings: Optional[str] = None,
    progress: gr.Progress = None
) -> Dict[str, Collection]:
    """Process HTR pipeline for multiple images and return processed collections."""
    
    results = {}
    temp_files = []
    
    total_images = len(image_paths)
    
    if custom_settings:
        try:
            config = json.loads(custom_settings)
        except json.JSONDecodeError:
            raise ValueError("Invalid JSON in custom_settings parameter. Please check your JSON syntax.")
    else:
        config = PIPELINE_CONFIGS[document_type]
    
    # Initialize pipeline once for all images
    pipeline = Pipeline.from_config(config)
    
    for idx, image_path in enumerate(image_paths):
        try:
            image_name = Path(image_path).stem if not image_path.startswith("http") else f"image_{idx+1}"
            
            if progress:
                progress((idx + 0.2) / total_images, 
                        desc=f"Processing image {idx+1}/{total_images}: {image_name}")
            
            # Handle image input
            processed_path = handle_image_input(image_path, progress, 
                                               desc_prefix=f"[{idx+1}/{total_images}] ")
            
            # Track temp files for cleanup
            if processed_path.startswith(tempfile.gettempdir()):
                temp_files.append(processed_path)
            
            if progress:
                progress((idx + 0.5) / total_images, 
                        desc=f"Running HTR on image {idx+1}/{total_images}: {image_name}")
            
            # Process with pipeline
            collection = Collection([processed_path])
            processed_collection = pipeline.run(collection)
            
            results[image_name] = processed_collection
            
            if progress:
                progress((idx + 1.0) / total_images, 
                        desc=f"Completed image {idx+1}/{total_images}: {image_name}")
            
        except Exception as e:
            results[image_name] = f"Error: {str(e)}"
            print(f"Error processing {image_path}: {str(e)}")
    
    # Cleanup temp files
    for temp_file in temp_files:
        try:
            os.unlink(temp_file)
        except:
            pass
    
    if progress:
        progress(1.0, desc=f"Completed processing all {total_images} images!")
    
    return results


def extract_text_from_collection(collection: Collection) -> str:
    """Extract and combine text from all nodes in the collection."""
    text_lines = []
    for page in collection.pages:
        for node in page.traverse():
            if hasattr(node, "text") and node.text:
                text_lines.append(node.text)
    return "\n".join(text_lines)


def htr_text(
    image_input: Union[str, List[str]],
    document_type: FormatChoices = "letter_swedish",
    custom_settings: Optional[str] = None,
    return_format: str = "separate",  # "separate" or "combined"
    progress: gr.Progress = gr.Progress()
) -> str:
    """
    Extract text from handwritten documents using HTR.
    Handles both single images and multiple images.
    
    Args:
        image_input: Single image path/URL, multiple paths/URLs (newline-separated), or list of uploaded files
        document_type: Type of document layout - choose based on your documents' structure and language
        custom_settings: Optional JSON configuration for advanced pipeline customization
        return_format: "separate" to show each document's text separately, "combined" to merge all text
        progress: Progress tracker for UI updates
        
    Returns:
        Extracted text from all handwritten documents
    """
    try:
        if progress:
            progress(0, desc="Starting HTR text extraction...")
        
        # Parse input to get list of images
        image_paths = parse_image_input(image_input)
        
        if not image_paths:
            return "No images provided. Please upload images or provide URLs."
        
        # Adjust description based on single vs multiple
        num_images = len(image_paths)
        desc = f"Processing {num_images} image{'s' if num_images > 1 else ''}..."
        
        if progress:
            progress(0.1, desc=desc)
        
        # Process all images
        results = _process_htr_pipeline_batch(
            image_paths, document_type, custom_settings, progress
        )
        
        # Extract text from results
        all_texts = []
        for image_name, collection in results.items():
            if isinstance(collection, str):  # Error case
                all_texts.append(f"=== {image_name} ===\n{collection}\n")
            else:
                text = extract_text_from_collection(collection)
                if return_format == "separate":
                    all_texts.append(f"=== {image_name} ===\n{text}\n")
                else:
                    all_texts.append(text)
        
        # Return formatted result
        if return_format == "separate":
            return "\n".join(all_texts)
        else:
            return "\n\n".join(all_texts)
        
    except ValueError as e:
        return f"Input error: {str(e)}"
    except Exception as e:
        return f"HTR text extraction failed: {str(e)}"


def htr_generate_files(
    image_input: Union[str, List[str]],
    document_type: FormatChoices = "letter_swedish",
    output_format: FileChoices = DEFAULT_OUTPUT,
    custom_settings: Optional[str] = None,
    progress: gr.Progress = gr.Progress()
) -> str:
    """
    Process handwritten documents and generate formatted output files.
    Returns a ZIP file for multiple documents, or single file for single document.
    
    Args:
        image_input: Single image path/URL, multiple paths/URLs (newline-separated), or list of uploaded files
        document_type: Type of document layout - affects segmentation and reading order
        output_format: Desired output format (txt for plain text, alto/page for XML with coordinates, json for structured data)
        custom_settings: Optional JSON configuration for advanced pipeline customization
        progress: Progress tracker for UI updates
        
    Returns:
        Path to generated file(s)
    """
    try:
        if progress:
            progress(0, desc="Starting HTR file processing...")
        
        # Parse input to get list of images
        image_paths = parse_image_input(image_input)
        
        if not image_paths:
            error_file = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt')
            error_file.write("No images provided. Please upload images or provide URLs.")
            error_file.close()
            return error_file.name
        
        num_images = len(image_paths)
        
        if progress:
            progress(0.1, desc=f"Processing {num_images} image{'s' if num_images > 1 else ''}...")
        
        # Process all images
        results = _process_htr_pipeline_batch(
            image_paths, document_type, custom_settings, progress
        )
        
        if progress:
            progress(0.9, desc="Creating output files...")
        
        # Create temporary directory for output files
        temp_dir = Path(tempfile.mkdtemp())
        output_files = []
        
        for image_name, collection in results.items():
            if isinstance(collection, str):  # Error case
                # Write error to text file
                error_file_path = temp_dir / f"{image_name}_error.txt"
                with open(error_file_path, 'w') as f:
                    f.write(collection)
                output_files.append(error_file_path)
            else:
                # Save collection in requested format
                export_dir = temp_dir / image_name
                collection.save(directory=str(export_dir), serializer=output_format)
                
                # Find and rename the generated file
                for root, _, files in os.walk(export_dir):
                    for file in files:
                        old_path = Path(root) / file
                        file_ext = Path(file).suffix
                        new_filename = (
                            f"{image_name}.{output_format}"
                            if not file_ext
                            else f"{image_name}{file_ext}"
                        )
                        new_path = temp_dir / new_filename
                        shutil.move(str(old_path), str(new_path))
                        output_files.append(new_path)
                        break
        
        # Return single file or ZIP based on input count
        if len(output_files) == 1 and len(image_paths) == 1:
            # Single file - return directly
            if progress:
                progress(1.0, desc="Processing complete!")
            return str(output_files[0])
        else:
            # Multiple files - create ZIP
            zip_path = temp_dir / f"htr_output_{output_format}.zip"
            with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
                for file_path in output_files:
                    zipf.write(file_path, file_path.name)
            
            if progress:
                progress(1.0, desc=f"Processing complete! Generated {len(output_files)} files.")
            
            return str(zip_path)
        
    except ValueError as e:
        error_file = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt')
        error_file.write(f"Input error: {str(e)}")
        error_file.close()
        return error_file.name
    except Exception as e:
        error_file = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt')
        error_file.write(f"HTR file generation failed: {str(e)}")
        error_file.close()
        return error_file.name


def htr_visualize(
    image_input: Union[str, List[str]],
    htr_documents: Union[List[str], None],
    progress: gr.Progress = gr.Progress()
) -> str:
    """
    Create visualizations for HTR results overlaid on original documents.
    Returns a ZIP file for multiple documents, or single image for single document.
    
    Args:
        image_input: Original document image paths/URLs (newline-separated if string)
        htr_documents: HTR output files (ALTO/PAGE XML) - must match order of images
        progress: Progress tracker for UI updates
        
    Returns:
        Path to visualization file(s)
    """
    try:
        if progress:
            progress(0, desc="Starting visualization generation...")
        
        # Parse inputs
        image_paths = parse_image_input(image_input)
        
        # Handle htr_documents - it should be a list of file paths
        if not htr_documents:
            raise ValueError("No HTR documents provided")
        
        # If htr_documents is a list of file objects from Gradio, extract paths
        htr_paths = []
        if isinstance(htr_documents, list):
            for doc in htr_documents:
                if isinstance(doc, str):
                    htr_paths.append(doc)
                elif hasattr(doc, 'name'):
                    htr_paths.append(doc.name)
                else:
                    htr_paths.append(str(doc))
        else:
            # Single file case
            if isinstance(htr_documents, str):
                htr_paths = [htr_documents]
            elif hasattr(htr_documents, 'name'):
                htr_paths = [htr_documents.name]
            else:
                htr_paths = [str(htr_documents)]
        
        if not image_paths:
            raise ValueError("No images provided")
        
        if len(image_paths) != len(htr_paths):
            raise ValueError(f"Number of images ({len(image_paths)}) doesn't match number of HTR documents ({len(htr_paths)})")
        
        num_docs = len(image_paths)
        
        if progress:
            progress(0.1, desc=f"Creating visualization{'s' if num_docs > 1 else ''} for {num_docs} document{'s' if num_docs > 1 else ''}...")
        
        temp_dir = Path(tempfile.mkdtemp())
        output_files = []
        temp_files = []
        
        for idx, (image_path, htr_path) in enumerate(zip(image_paths, htr_paths)):
            try:
                image_name = Path(image_path).stem if not image_path.startswith("http") else f"image_{idx+1}"
                
                if progress:
                    progress((idx + 0.3) / num_docs, 
                            desc=f"Visualizing document {idx+1}/{num_docs}: {image_name}")
                
                # Handle image input
                processed_image = handle_image_input(image_path, progress, 
                                                    desc_prefix=f"[{idx+1}/{num_docs}] ")
                if processed_image.startswith(tempfile.gettempdir()):
                    temp_files.append(processed_image)
                
                # Generate visualization - use the last parameter for output path
                output_viz_path = str(temp_dir / f"{image_name}_visualization.png")
                viz_result = htrflow_visualizer(processed_image, htr_path, output_viz_path)
                
                # Check if visualization was created
                if os.path.exists(output_viz_path):
                    output_files.append(Path(output_viz_path))
                elif viz_result and os.path.exists(viz_result):
                    # Fallback: if viz_result points to a different file
                    viz_path = temp_dir / f"{image_name}_visualization.png"
                    shutil.move(viz_result, str(viz_path))
                    output_files.append(viz_path)
                else:
                    raise ValueError("Visualization generation failed - no output file created")
                
            except Exception as e:
                # Create error file for this visualization
                error_path = temp_dir / f"{image_name}_viz_error.txt"
                with open(error_path, 'w') as f:
                    f.write(f"Visualization failed: {str(e)}")
                output_files.append(error_path)
                print(f"Error visualizing {image_name}: {str(e)}")
        
        # Cleanup temp files
        for temp_file in temp_files:
            try:
                os.unlink(temp_file)
            except:
                pass
        
        # Return single file or ZIP based on input count
        if len(output_files) == 1 and num_docs == 1:
            # Single visualization - return directly
            if progress:
                progress(1.0, desc="Visualization complete!")
            return str(output_files[0])
        else:
            # Multiple visualizations - create ZIP
            if progress:
                progress(0.9, desc="Creating ZIP archive...")
            
            zip_path = temp_dir / "htr_visualizations.zip"
            with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
                for file_path in output_files:
                    zipf.write(file_path, file_path.name)
            
            if progress:
                progress(1.0, desc=f"Visualization complete! Created {len(output_files)} visualization{'s' if len(output_files) > 1 else ''}.")
            
            return str(zip_path)
        
    except Exception as e:
        error_file = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt')
        error_file.write(f"Visualization failed: {str(e)}")
        error_file.close()
        return error_file.name


def create_htrflow_mcp_server():
    # HTR Text extraction interface
    htr_text_interface = gr.Interface(
        fn=htr_text,
        inputs=[
            gr.Textbox(
                label="Image Input",
                placeholder="Single image path/URL or multiple (one per line)\nYou can also drag and drop files here",
                lines=3
            ),
            gr.Dropdown(
                choices=FORMAT_CHOICES, 
                value="letter_swedish", 
                label="Document Type",
                info="Select the type that best matches your documents' layout and language"
            ),
            gr.Textbox(
                label="Custom Settings (JSON)",
                placeholder='{"steps": [...]} - Leave empty for default settings',
                value="",
                lines=3
            ),
            gr.Radio(
                choices=["separate", "combined"],
                value="separate",
                label="Output Format",
                info="'separate' shows each document's text with headers, 'combined' merges all text"
            ),
        ],
        outputs=[gr.Textbox(label="Extracted Text", lines=20)],
        title="Extract Text from Handwritten Documents",
        description="Process one or more handwritten document images. Works with letters and book spreads in English and Swedish.",
        api_name="htr_text",
    )

    # HTR File generation interface
    htr_files_interface = gr.Interface(
        fn=htr_generate_files,
        inputs=[
            gr.Textbox(
                label="Image Input",
                placeholder="Single image path/URL or multiple (one per line)\nYou can also drag and drop files here",
                lines=3
            ),
            gr.Dropdown(
                choices=FORMAT_CHOICES, 
                value="letter_swedish", 
                label="Document Type",
                info="Select the type that best matches your documents' layout and language"
            ),
            gr.Dropdown(
                choices=FILE_CHOICES, 
                value=DEFAULT_OUTPUT, 
                label="Output Format",
                info="ALTO/PAGE: XML with coordinates | JSON: Structured data | TXT: Plain text only"
            ),
            gr.Textbox(
                label="Custom Settings (JSON)",
                placeholder='{"steps": [...]} - Leave empty for default settings',
                value="",
                lines=3
            ),
        ],
        outputs=[gr.File(label="Download HTR Output")],
        title="Generate HTR Output Files",
        description="Process handwritten documents and export in various formats. Returns ZIP for multiple files.",
        api_name="htr_generate_files",
    )

    # HTR Visualization interface
    htr_viz_interface = gr.Interface(
        fn=htr_visualize,
        inputs=[
            gr.Textbox(
                label="Original Image Paths/URLs",
                placeholder="One path/URL per line",
                lines=3
            ),
            gr.File(
                label="Upload HTR XML Files (ALTO/PAGE)", 
                file_types=[".xml"],
                file_count="multiple"
            ),
        ],
        outputs=gr.File(label="Download Visualization"),
        title="Visualize HTR Results",
        description="Create annotated images showing detected regions and text. Files must be in matching order.",
        api_name="htr_visualize",
    )

    # Create tabbed interface
    demo = gr.TabbedInterface(
        [
            htr_text_interface,
            htr_files_interface, 
            htr_viz_interface,
        ],
        [
            "📚 Extract Text",
            "📁 Generate Files",
            "🖼️ Visualize Results",
        ],
        title="🖋️ HTRflow - Handwritten Text Recognition",
        analytics_enabled=False,
    )

    return demo


if __name__ == "__main__":
    demo = create_htrflow_mcp_server()
    demo.launch(
        mcp_server=True, 
        share=False, 
        debug=False,
        show_api=True,  
        favicon_path=None,
    )