imperiusrex commited on
Commit
54ee64b
·
verified ·
1 Parent(s): 1eb67a7

Initial commit of Handwritten OCR Gradio Space

Browse files
Files changed (2) hide show
  1. app.py +125 -0
  2. requirements.txt +9 -0
app.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ import torch
4
+ from transformers import TrOCRProcessor, VisionEncoderDecoderModel
5
+ from PIL import Image
6
+ import cv2
7
+ import numpy as np
8
+ from paddleocr import PaddleOCR # Ensure paddleocr is installed and its dependencies are met
9
+
10
+ # --- Global Model Loading ---
11
+ # Load the pre-trained TrOCR model and processor from Hugging Face Hub
12
+ # IMPORTANT: Replace "your-username/my-handwritten-trocr" with your actual model's repository ID
13
+ # If your model is also under 'imperiusrex', it would be "imperiusrex/my-handwritten-trocr"
14
+ try:
15
+ processor = TrOCRProcessor.from_pretrained("your-username/my-handwritten-trocr")
16
+ model = VisionEncoderDecoderModel.from_pretrained("your-username/my-handwritten-trocr")
17
+ model.eval() # Set model to evaluation mode
18
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
19
+ model.to(device)
20
+ print(f"TrOCR model loaded successfully on {device}.")
21
+ except Exception as e:
22
+ print(f"Error loading TrOCR model: {e}")
23
+ processor = None
24
+ model = None
25
+
26
+ # Initialize PaddleOCR for text detection
27
+ # It will download necessary models on first run, which might take some time.
28
+ # Ensure 'paddlepaddle' is installed in your requirements.txt
29
+ try:
30
+ # Note: PaddleOCR will download models to ~/.paddleocr/ on the Space.
31
+ # The det_model_dir, rec_model_dir, cls_model_dir parameters are typically for local inference.
32
+ # For a Hugging Face Space, you usually let PaddleOCR download its models automatically.
33
+ # If you face issues, consider adding a post_install.sh script to pre-download them.
34
+ det_model = PaddleOCR(use_angle_cls=False, lang='en') # Removed local paths for Space deployment
35
+ print("PaddleOCR detection model initialized successfully.")
36
+ except Exception as e:
37
+ print(f"Error initializing PaddleOCR: {e}")
38
+ det_model = None
39
+
40
+ # --- Prediction Function ---
41
+ def recognize_handwritten_text(image_input: Image.Image) -> str:
42
+ """
43
+ Processes an input image to detect and recognize handwritten text.
44
+ """
45
+ if processor is None or model is None:
46
+ return "Error: TrOCR model not loaded. Please check logs."
47
+ if det_model is None:
48
+ return "Error: PaddleOCR detection model not loaded. Please check logs."
49
+
50
+ # Convert PIL Image to OpenCV format (numpy array)
51
+ img_cv2 = cv2.cvtColor(np.array(image_input), cv2.COLOR_RGB2BGR)
52
+
53
+ try:
54
+ result = det_model.ocr(img_cv2, det=True, rec=False, cls=False)
55
+
56
+ detected_boxes = []
57
+ if result and result[0]: # Check if result is not empty and first page exists
58
+ for line in result[0]:
59
+ detected_boxes.append(line[0]) # line[0] is the bounding box
60
+
61
+ if not detected_boxes:
62
+ return "No text detected in the image."
63
+
64
+ except Exception as e:
65
+ print(f"Error during text detection: {e}")
66
+ return f"Error during text detection: {e}"
67
+
68
+ all_recognized_texts = []
69
+
70
+ # Process each detected box
71
+ for i, box in enumerate(detected_boxes):
72
+ box = np.array(box, dtype=np.float32) # shape: (4, 2)
73
+
74
+ # Compute width and height for perspective warp
75
+ width_a = np.linalg.norm(box[0] - box[1])
76
+ width_b = np.linalg.norm(box[2] - box[3])
77
+ height_a = np.linalg.norm(box[0] - box[3])
78
+ height_b = np.linalg.norm(box[1] - box[2])
79
+
80
+ width = int(max(width_a, width_b))
81
+ height = int(max(height_a, height_b))
82
+
83
+ # Destination rectangle for warp
84
+ dst_rect = np.array([
85
+ [0, 0],
86
+ [width - 1, 0],
87
+ [width - 1, height - 1],
88
+ [0, height - 1]
89
+ ], dtype=np.float32)
90
+
91
+ # Perspective transform
92
+ M = cv2.getPerspectiveTransform(box, dst_rect)
93
+ warped_cv2 = cv2.warpPerspective(img_cv2, M, (width, height))
94
+
95
+ # Convert warped image back to PIL for TrOCR
96
+ warped_pil = Image.fromarray(cv2.cvtColor(warped_cv2, cv2.COLOR_BGR2RGB))
97
+
98
+ # Preprocess for TrOCR
99
+ pixel_values = processor(images=warped_pil, return_tensors="pt").pixel_values.to(device)
100
+
101
+ # Generate prediction with TrOCR
102
+ with torch.no_grad():
103
+ generated_ids = model.generate(pixel_values, max_new_tokens=64)
104
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
105
+ all_recognized_texts.append(generated_text)
106
+
107
+ return "\n".join(all_recognized_texts)
108
+
109
+ # --- Gradio Interface ---
110
+ iface = gr.Interface(
111
+ fn=recognize_handwritten_text,
112
+ inputs=gr.Image(type="pil", label="Upload Handwritten Image"),
113
+ outputs=gr.Textbox(label="Recognized Text"),
114
+ title="Handwritten Text Recognition with TrOCR and PaddleOCR",
115
+ description="Upload an image containing handwritten text. The model will first detect text regions using PaddleOCR, then recognize the text in each region using a fine-tuned TrOCR model.",
116
+ allow_flagging="never", # Disable flagging for this demo
117
+ examples=[
118
+ # You can add example images here for users to try
119
+ # Example: "path/to/your/example_image.png"
120
+ ]
121
+ )
122
+
123
+ # Launch the Gradio app
124
+ if __name__ == "__main__":
125
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+
2
+ transformers
3
+ torch
4
+ Pillow
5
+ gradio
6
+ opencv-python
7
+ numpy
8
+ paddlepaddle==2.6.0
9
+ paddleocr==2.7.0.3