Mohamed-Riyaz's picture
Update app.py
b3ec4c2 verified
Raw History Blame Contribute Delete
3.69 kB
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)