File size: 3,690 Bytes
b3ec4c2
fd4d5da
b3ec4c2
 
 
fd4d5da
b3ec4c2
 
fd4d5da
b3ec4c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd4d5da
b3ec4c2
 
 
 
 
 
fd4d5da
b3ec4c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd4d5da
b3ec4c2
 
 
 
fd4d5da
b3ec4c2
 
 
fd4d5da
b3ec4c2
 
 
 
fd4d5da
b3ec4c2
 
fd4d5da
b3ec4c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd4d5da
 
b3ec4c2
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
import gradio as gr
import easyocr
import numpy as np
from PIL import Image
import os

# Initialize OCR reader
reader = easyocr.Reader(['en'], gpu=False)

def extract_text(image):
    """Extract text from uploaded image"""
    if image is None:
        return "Please upload an image", "No text", "0", "0"
    
    try:
        # Convert PIL image to numpy array
        image_np = np.array(image)
        
        # Perform OCR
        result = reader.readtext(image_np, detail=0, paragraph=True)
        
        if result:
            text = "\n".join(result)
            char_count = len(text)
            word_count = len(text.split())
            return text, f"βœ“ {char_count} characters", f"βœ“ {word_count} words", "βœ… Text detected!"
        else:
            return "No text detected in the image. Please try another image.", "0", "0", "⚠️ No text found"
            
    except Exception as e:
        return f"Error processing image: {str(e)}", "Error", "Error", "❌ Error"

# Create Gradio interface
with gr.Blocks(title="OCR Text Extractor", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""

    # πŸ“ OCR Text Extractor

    ### Upload an image and extract text from it instantly

    """)
    
    with gr.Row():
        with gr.Column(scale=1):
            image_input = gr.Image(
                label="Upload Image",
                type="pil",
                height=300
            )
            extract_btn = gr.Button("πŸ” Extract Text", variant="primary")
            
        with gr.Column(scale=1):
            text_output = gr.Textbox(
                label="Extracted Text",
                lines=12,
                placeholder="Text will appear here..."
            )
            with gr.Row():
                char_count = gr.Textbox(label="Characters", value="0", interactive=False)
                word_count = gr.Textbox(label="Words", value="0", interactive=False)
            status = gr.Textbox(label="Status", value="Ready", interactive=False)
    
    with gr.Row():
        copy_btn = gr.Button("πŸ“‹ Copy to Clipboard", variant="secondary")
        download_btn = gr.Button("πŸ’Ύ Download as TXT", variant="secondary")
        clear_btn = gr.Button("πŸ”„ Clear", variant="stop")
    
    # Functions for buttons
    def copy_text(text):
        return text
    
    def download_text(text):
        if text and text != "No text detected in the image. Please try another image.":
            return text
        return ""
    
    def clear_all():
        return None, "", "0", "0", "Ready"
    
    # Connect events
    extract_btn.click(
        extract_text,
        inputs=[image_input],
        outputs=[text_output, char_count, word_count, status]
    )
    
    copy_btn.click(
        fn=None,
        inputs=[text_output],
        js="(text) => { navigator.clipboard.writeText(text); }"
    )
    
    download_btn.click(
        fn=None,
        inputs=[text_output],
        js="(text) => { const blob = new Blob([text], {type: 'text/plain'}); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'extracted_text.txt'; a.click(); }"
    )
    
    clear_btn.click(
        clear_all,
        inputs=[],
        outputs=[image_input, text_output, char_count, word_count, status]
    )
    
    # Example images
    gr.Markdown("""

    ### πŸ“Έ Try with example images

    Upload any image with text, or try these examples:

    - Receipts

    - Business cards

    - Book pages

    - Signs

    """)

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)