File size: 9,850 Bytes
edf3f62
58c54a2
186fd60
58c54a2
 
 
ff9681b
59edac2
 
 
be4764f
343dd2c
 
 
f6fe3e1
58c54a2
 
 
186fd60
58c54a2
59edac2
58c54a2
 
 
 
 
343dd2c
 
 
 
 
 
 
 
59edac2
343dd2c
 
 
 
 
 
58c54a2
 
343dd2c
 
58c54a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
343dd2c
 
 
 
 
 
 
 
58c54a2
343dd2c
58c54a2
343dd2c
58c54a2
 
343dd2c
 
 
58c54a2
 
 
 
 
343dd2c
 
58c54a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6fe3e1
6302661
186fd60
58c54a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6302661
 
 
 
 
 
 
 
 
 
 
58c54a2
 
186fd60
58c54a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc0862c
58c54a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d25f8e
 
 
 
 
 
 
 
 
 
 
 
 
58c54a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186fd60
58c54a2
186fd60
58c54a2
 
893b675
58c54a2
 
 
 
 
6302661
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
import gradio as gr
import torch
from PIL import Image
import logging
from typing import Optional, Union
import os
import spaces
from dotenv import load_dotenv

load_dotenv()

# Disable torch compilation to avoid dynamo issues
torch._dynamo.config.disable = True
torch.backends.cudnn.allow_tf32 = True

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class AtlasOCR:
    def __init__(self, model_name: str = "atlasia/AtlasOCR", max_tokens: int = 2000):
        """Initialize the AtlasOCR model with proper error handling."""
        try:
            from unsloth import FastVisionModel
            
            logger.info(f"Loading model: {model_name}")
            
            # Disable compilation for the model
            with torch._dynamo.config.patch(disable=True):
                self.model, self.processor = FastVisionModel.from_pretrained(
                    model_name,
                    device_map="auto",
                    load_in_4bit=True,
                    use_gradient_checkpointing="unsloth",
                    token=os.environ["HF_API_KEY"]
                )
            
            # Ensure model is not compiled
            if hasattr(self.model, '_dynamo_compile'):
                self.model._dynamo_compile = False
                
            self.max_tokens = max_tokens
            self.prompt = ""
            self.device = next(self.model.parameters()).device
            logger.info(f"Model loaded successfully on device: {self.device}")
            
        except ImportError:
            logger.error("unsloth not found. Please install it: pip install unsloth")
            raise
        except Exception as e:
            logger.error(f"Error loading model: {e}")
            raise

    def prepare_inputs(self, image: Image.Image) -> dict:
        """Prepare inputs for the model with proper error handling."""
        try:
            messages = [
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "image",
                        },
                        {"type": "text", "text": self.prompt},
                    ],
                }
            ]

            text = self.processor.apply_chat_template(
                messages, tokenize=False, add_generation_prompt=True
            )

            inputs = self.processor(
                image,
                text,
                add_special_tokens=False,
                return_tensors="pt",
            )
            return inputs
            
        except Exception as e:
            logger.error(f"Error preparing inputs: {e}")
            raise

    def predict(self, image: Image.Image) -> str:
        """Predict text from image with comprehensive error handling."""
        try:
            if image is None:
                return "Please upload an image."
            
            # Convert numpy array to PIL Image if needed
            if hasattr(image, 'shape'):  # numpy array
                image = Image.fromarray(image)
            
            inputs = self.prepare_inputs(image)
            
            # Move inputs to the same device as model with explicit device handling
            device = self.device
            logger.info(f"Moving inputs to device: {device}")
            
            # Manually move each tensor to device
            for key in inputs:
                if hasattr(inputs[key], 'to'):
                    inputs[key] = inputs[key].to(device)
            
            # Ensure attention_mask is float32 and on correct device
            if 'attention_mask' in inputs:
                inputs['attention_mask'] = inputs['attention_mask'].to(dtype=torch.float32, device=device)
            
            logger.info(f"Generating text with max_tokens={self.max_tokens}")
            
            # Disable compilation during generation
            with torch.no_grad(), torch._dynamo.config.patch(disable=True):
                generated_ids = self.model.generate(
                    **inputs, 
                    max_new_tokens=self.max_tokens, 
                    use_cache=True,
                    do_sample=False,
                    temperature=0.1,
                    pad_token_id=self.processor.tokenizer.eos_token_id
                )
            
            generated_ids_trimmed = [
                out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs['input_ids'], generated_ids)
            ]
            
            output_text = self.processor.batch_decode(
                generated_ids_trimmed, 
                skip_special_tokens=True, 
                clean_up_tokenization_spaces=False
            )
            
            result = output_text[0].strip()
            logger.info(f"Generated text: {result[:100]}...")
            return result
            
        except Exception as e:
            logger.error(f"Error during prediction: {e}")
            return f"Error processing image: {str(e)}"

    def __call__(self, image: Union[Image.Image, str]) -> str:
        """Callable interface for the model."""
        if isinstance(image, str):
            return "Please upload an image file."
        return self.predict(image)


# Global model instance
atlas_ocr = None

def load_model():
    """Load the model globally to avoid reloading."""
    global atlas_ocr
    if atlas_ocr is None:
        try:
            atlas_ocr = AtlasOCR()
        except Exception as e:
            logger.error(f"Failed to load model: {e}")
            return False
    return True

@spaces.GPU
def perform_ocr(image):
    """Main OCR function with proper error handling."""
    try:
        if not load_model():
            return "Error: Failed to load model. Please check the logs."
        
        if image is None:
            return "Please upload an image to extract text."
        
        result = atlas_ocr(image)
        return result
        
    except Exception as e:
        logger.error(f"Error in perform_ocr: {e}")
        return f"An error occurred: {str(e)}"

def process_with_status(image):
    """Process image and return result with status - moved outside to avoid pickling issues."""
    if image is None:
        return "Please upload an image.", "No image provided"
    
    try:
        result = perform_ocr(image)
        return result, "Processing completed successfully"
    except Exception as e:
        return f"Error: {str(e)}", f"Error occurred: {str(e)}"

def create_interface():
    """Create the Gradio interface with proper configuration."""
    
    
    with gr.Blocks(
        title="AtlasOCR - Darija Document OCR",
        theme=gr.themes.Soft(),
        css="""
        .gradio-container {
            max-width: 1200px !important;
        }
        """
    ) as demo:
        
        gr.Markdown("""
        # AtlasOCR - Darija Document OCR
        Upload an image to extract Darija text in real-time. This model is specialized for Darija document OCR.
        """)
        
        with gr.Row():
            with gr.Column(scale=1):
                # Input image
                image_input = gr.Image(
                    type="pil", 
                    label="Upload Image",
                    height=400
                )
                # Submit button
                submit_btn = gr.Button(
                    "Extract Text", 
                    variant="primary",
                    size="lg"
                )
                
                # Clear button
                clear_btn = gr.Button("Clear", variant="secondary")

            with gr.Column(scale=1):
                # Output text
                output = gr.Textbox(
                    label="Extracted Text", 
                    lines=20, 
                    show_copy_button=True,
                    placeholder="Extracted text will appear here..."
                )
                
                # Status indicator
                status = gr.Textbox(
                    label="Status",
                    value="Ready to process images",
                    interactive=False
                )
                
                # Model details
                with gr.Accordion("Model Information", open=False):
                    gr.Markdown("""
                    **Model:** AtlasOCR-v0
                    **Description:** Specialized Darija OCR model for Arabic dialect text extraction
                    **Size:** 3B parameters
                    **Context window:** Supports up to 2000 output tokens
                    **Optimization:** 4-bit quantization for efficient inference
                    """)

        gr.Examples(
                    examples=[
                        ["i3.png"],
                        ["i6.png"]
                    ],
                    inputs=image_input,
                    outputs=[output, status],   # <-- required
                    fn=process_with_status,     # <-- required
                    label="Example Images",
                    examples_per_page=4,
                    cache_examples=True
                )
        # Set up processing flow
        submit_btn.click(
            fn=process_with_status, 
            inputs=image_input, 
            outputs=[output, status]
        )
        
        image_input.change(
            fn=process_with_status, 
            inputs=image_input, 
            outputs=[output, status]
        )
        
        clear_btn.click(
            fn=lambda: (None, "", "Ready to process images"),
            outputs=[image_input, output, status]
        )
    
    return demo

# Create and launch the interface
if __name__ == "__main__":
    demo = create_interface()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        debug=True
    )