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)