Ali0044 commited on
Commit
15e3cdb
·
verified ·
1 Parent(s): 3923d73

Upload README.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +21 -42
README.md CHANGED
@@ -10,13 +10,13 @@ tags:
10
  - pytorch
11
  ---
12
 
13
- # Qalam-Net (قلم-نت): Advanced Arabic OCR
14
 
15
- Qalam-Net is a high-performance, cross-backend Optical Character Recognition (OCR) model for Arabic. Built on **Keras 3**, it supports **JAX**, **PyTorch**, and **TensorFlow** backends.
16
 
17
- ## 🚀 Quick Start (Advanced Usage)
18
 
19
- To use Qalam-Net, you must define the `CTCLayer` (used during training) and pass it as a custom object.
20
 
21
  ### 1. Installation
22
  ```bash
@@ -26,69 +26,48 @@ pip install -U "keras>=3.0" jax jaxlib huggingface_hub opencv-python
26
  ### 2. Implementation
27
  ```python
28
  import os
29
- os.environ["KERAS_BACKEND"] = "jax" # Switch to "tensorflow" or "torch" if preferred
30
 
31
  import keras
32
- from keras import layers
33
  import numpy as np
34
  import cv2
35
- from huggingface_hub import hf_hub_download
36
-
37
- # [MANDATORY] Define the CTCLayer for deserialization
38
- @keras.saving.register_keras_serializable()
39
- class CTCLayer(layers.Layer):
40
- def __init__(self, name=None, **kwargs):
41
- super().__init__(name=name, **kwargs)
42
- self.loss_fn = keras.backend.ctc_batch_cost
43
-
44
- def call(self, y_true, y_pred):
45
- return y_pred
46
 
47
  class QalamNet:
48
  def __init__(self, repo_id="Ali0044/Qalam-Net"):
49
- # Download the model
50
- model_path = hf_hub_download(repo_id=repo_id, filename="model.keras")
51
-
52
- # Load with custom_objects
53
- self.model = keras.saving.load_model(
54
- model_path,
55
- custom_objects={"CTCLayer": CTCLayer},
56
- compile=False
57
- )
58
 
59
  # Standard Arabic Vocabulary
60
  self.vocab = [' ', '!', '"', '#', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '=', '?', '[', ']', 'ء', 'آ', 'أ', 'ؤ', 'إ', 'ئ', 'ا', 'ب', 'ة', 'ت', 'ث', 'ج', 'ح', 'خ', 'د', 'ذ', 'ر', 'ز', 'س', 'ش', 'ص', 'ض', 'ط', 'ظ', 'ع', 'غ', 'ـ', 'ف', 'ق', 'ك', 'ل', 'م', 'ن', 'ه', 'و', 'ى', 'ي', 'ً', 'ٌ', 'ٍ', 'َ', 'ُ', 'ِ', 'ّ', 'ْ', '٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩']
61
 
62
  def preprocess(self, image_path):
63
  img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
64
- img = cv2.resize(img, (128, 32))
65
- img = (img / 255.0).astype(np.float32)
66
- img = img.T
67
- img = np.expand_dims(img, axis=-1)
68
- return np.expand_dims(img, axis=0)
69
 
70
  def predict(self, image_path):
71
  batch_img = self.preprocess(image_path)
72
- # The model has 2 inputs [image, label] but we only need image for prediction
73
- # We can pass dummy labels or use the internal prediction layers
74
- preds = self.model.predict([batch_img, np.zeros((1, 1))])
75
 
76
  # CTC Decode
77
- input_len = np.ones(preds.shape[0]) * preds.shape[1]
78
- results = keras.backend.ctc_decode(preds, input_length=input_len, greedy=True)[0][0]
79
 
80
  return "".join([self.vocab[int(res)] for res in results[0] if res != -1])
81
 
82
- # Usage
83
  # ocr = QalamNet()
84
- # print(ocr.predict("text.png"))
85
  ```
86
 
87
  ## 🧠 Model Architecture
88
  Qalam-Net employs a specialized **CNN-BiLSTM-Attention** pipeline:
89
- - **Spatial Features**: 3-block CNN for robust feature extraction.
90
- - **Sequence Context**: Dual Bidirectional LSTMs to capture Arabic script flow.
91
- - **Focus Mechanism**: Self-attention layer for character-level precision.
92
 
93
  ---
94
- **Developed by [Ali Khalid](https://github.com/Ali0044)**
 
10
  - pytorch
11
  ---
12
 
13
+ # Qalam-Net (قلم-نت): Advanced Arabic OCR (v2 Portable)
14
 
15
+ Qalam-Net is a high-performance, cross-backend Optical Character Recognition (OCR) model for Arabic. This version (**v2**) has been patched for maximum portability across Keras versions and optimized for inference.
16
 
17
+ ## 🚀 Quick Start (Clean Inference)
18
 
19
+ Qalam-Net v2 no longer requires custom layers or complex setup during inference.
20
 
21
  ### 1. Installation
22
  ```bash
 
26
  ### 2. Implementation
27
  ```python
28
  import os
29
+ os.environ["KERAS_BACKEND"] = "jax" # Options: "jax", "tensorflow", "torch"
30
 
31
  import keras
 
32
  import numpy as np
33
  import cv2
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  class QalamNet:
36
  def __init__(self, repo_id="Ali0044/Qalam-Net"):
37
+ # Load the portable model directly from Hugging Face
38
+ # No 'custom_objects' or 'CTCLayer' required!
39
+ self.model = keras.saving.load_model(f"hf://{repo_id}")
 
 
 
 
 
 
40
 
41
  # Standard Arabic Vocabulary
42
  self.vocab = [' ', '!', '"', '#', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '=', '?', '[', ']', 'ء', 'آ', 'أ', 'ؤ', 'إ', 'ئ', 'ا', 'ب', 'ة', 'ت', 'ث', 'ج', 'ح', 'خ', 'د', 'ذ', 'ر', 'ز', 'س', 'ش', 'ص', 'ض', 'ط', 'ظ', 'ع', 'غ', 'ـ', 'ف', 'ق', 'ك', 'ل', 'م', 'ن', 'ه', 'و', 'ى', 'ي', 'ً', 'ٌ', 'ٍ', 'َ', 'ُ', 'ِ', 'ّ', 'ْ', '٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩']
43
 
44
  def preprocess(self, image_path):
45
  img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
46
+ img = cv2.resize(img, (128, 32)) / 255.0
47
+ img = img.T # (Height, Width) -> (Width, Height)
48
+ img = np.expand_dims(img, axis=(-1, 0)) # Add Channel and Batch
49
+ return img.astype(np.float32)
 
50
 
51
  def predict(self, image_path):
52
  batch_img = self.preprocess(image_path)
53
+ predictions = self.model.predict(batch_img)
 
 
54
 
55
  # CTC Decode
56
+ input_len = np.ones(predictions.shape[0]) * predictions.shape[1]
57
+ results = keras.backend.ctc_decode(predictions, input_length=input_len, greedy=True)[0][0]
58
 
59
  return "".join([self.vocab[int(res)] for res in results[0] if res != -1])
60
 
61
+ # Run
62
  # ocr = QalamNet()
63
+ # print(f"Output: {ocr.predict('test_sample.png')}")
64
  ```
65
 
66
  ## 🧠 Model Architecture
67
  Qalam-Net employs a specialized **CNN-BiLSTM-Attention** pipeline:
68
+ - **CNN Backbone**: Extracts high-level spatial features from Arabic script.
69
+ - **BiLSTM Layers**: Captures the sequential nature of right-to-left writing.
70
+ - **Attention Mechanism**: Resolves difficult character boundaries.
71
 
72
  ---
73
+ **Maintained by [Ali Khalid](https://github.com/Ali0044)**