Mohamed-Riyaz commited on
Commit
b3ec4c2
Β·
verified Β·
1 Parent(s): 5b56e67

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -72
app.py CHANGED
@@ -1,84 +1,113 @@
1
- from flask import Flask, render_template, request, flash, redirect, url_for
2
- import os
3
  import easyocr
4
- import logging
5
- from werkzeug.utils import secure_filename
6
- import time
7
- import tempfile
8
-
9
- app = Flask(__name__)
10
- app.secret_key = os.environ.get('SECRET_KEY', 'your-secret-key-here')
11
-
12
- # Configuration
13
- UPLOAD_FOLDER = "uploads"
14
- ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp'}
15
- MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
16
-
17
- app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
18
- app.config["MAX_CONTENT_LENGTH"] = MAX_FILE_SIZE
19
-
20
- # Setup logging
21
- logging.basicConfig(level=logging.INFO)
22
-
23
- # Initialize OCR reader (lazy loading for better performance)
24
- reader = None
25
-
26
- def get_reader():
27
- global reader
28
- if reader is None:
29
- # Use CPU mode for Hugging Face
30
- reader = easyocr.Reader(['en'], gpu=False)
31
- return reader
32
 
33
- def allowed_file(filename):
34
- return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
35
 
36
- @app.route('/')
37
- def home():
38
- return render_template("index.html")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- @app.route('/upload', methods=['POST'])
41
- def upload():
42
- start_time = time.time()
 
 
 
43
 
44
- if 'image' not in request.files:
45
- flash('No file uploaded')
46
- return redirect(url_for('home'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
- file = request.files['image']
 
 
 
49
 
50
- if file.filename == '':
51
- flash('No file selected')
52
- return redirect(url_for('home'))
53
 
54
- if not allowed_file(file.filename):
55
- flash('File type not allowed. Please upload an image.')
56
- return redirect(url_for('home'))
 
57
 
58
- try:
59
- filename = secure_filename(file.filename)
60
- filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
61
- file.save(filepath)
62
-
63
- # Process image with lazy-loaded reader
64
- ocr_reader = get_reader()
65
- result = ocr_reader.readtext(filepath, detail=0, paragraph=True)
66
-
67
- # Clean up
68
- os.remove(filepath)
69
-
70
- text = "\n".join(result) if result else "No text detected in the image. Please try another image."
71
-
72
- processing_time = round(time.time() - start_time, 2)
73
- logging.info(f"Processed {filename} in {processing_time}s")
74
-
75
- return render_template("result.html", text=text, processing_time=processing_time)
76
 
77
- except Exception as e:
78
- logging.error(f"Error processing image: {str(e)}")
79
- flash('Error processing image. Please try again.')
80
- return redirect(url_for('home'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
  if __name__ == "__main__":
83
- os.makedirs(UPLOAD_FOLDER, exist_ok=True)
84
- app.run(host="0.0.0.0", port=7860)
 
1
+ import gradio as gr
 
2
  import easyocr
3
+ import numpy as np
4
+ from PIL import Image
5
+ import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ # Initialize OCR reader
8
+ reader = easyocr.Reader(['en'], gpu=False)
9
 
10
+ def extract_text(image):
11
+ """Extract text from uploaded image"""
12
+ if image is None:
13
+ return "Please upload an image", "No text", "0", "0"
14
+
15
+ try:
16
+ # Convert PIL image to numpy array
17
+ image_np = np.array(image)
18
+
19
+ # Perform OCR
20
+ result = reader.readtext(image_np, detail=0, paragraph=True)
21
+
22
+ if result:
23
+ text = "\n".join(result)
24
+ char_count = len(text)
25
+ word_count = len(text.split())
26
+ return text, f"βœ“ {char_count} characters", f"βœ“ {word_count} words", "βœ… Text detected!"
27
+ else:
28
+ return "No text detected in the image. Please try another image.", "0", "0", "⚠️ No text found"
29
+
30
+ except Exception as e:
31
+ return f"Error processing image: {str(e)}", "Error", "Error", "❌ Error"
32
 
33
+ # Create Gradio interface
34
+ with gr.Blocks(title="OCR Text Extractor", theme=gr.themes.Soft()) as demo:
35
+ gr.Markdown("""
36
+ # πŸ“ OCR Text Extractor
37
+ ### Upload an image and extract text from it instantly
38
+ """)
39
 
40
+ with gr.Row():
41
+ with gr.Column(scale=1):
42
+ image_input = gr.Image(
43
+ label="Upload Image",
44
+ type="pil",
45
+ height=300
46
+ )
47
+ extract_btn = gr.Button("πŸ” Extract Text", variant="primary")
48
+
49
+ with gr.Column(scale=1):
50
+ text_output = gr.Textbox(
51
+ label="Extracted Text",
52
+ lines=12,
53
+ placeholder="Text will appear here..."
54
+ )
55
+ with gr.Row():
56
+ char_count = gr.Textbox(label="Characters", value="0", interactive=False)
57
+ word_count = gr.Textbox(label="Words", value="0", interactive=False)
58
+ status = gr.Textbox(label="Status", value="Ready", interactive=False)
59
 
60
+ with gr.Row():
61
+ copy_btn = gr.Button("πŸ“‹ Copy to Clipboard", variant="secondary")
62
+ download_btn = gr.Button("πŸ’Ύ Download as TXT", variant="secondary")
63
+ clear_btn = gr.Button("πŸ”„ Clear", variant="stop")
64
 
65
+ # Functions for buttons
66
+ def copy_text(text):
67
+ return text
68
 
69
+ def download_text(text):
70
+ if text and text != "No text detected in the image. Please try another image.":
71
+ return text
72
+ return ""
73
 
74
+ def clear_all():
75
+ return None, "", "0", "0", "Ready"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
+ # Connect events
78
+ extract_btn.click(
79
+ extract_text,
80
+ inputs=[image_input],
81
+ outputs=[text_output, char_count, word_count, status]
82
+ )
83
+
84
+ copy_btn.click(
85
+ fn=None,
86
+ inputs=[text_output],
87
+ js="(text) => { navigator.clipboard.writeText(text); }"
88
+ )
89
+
90
+ download_btn.click(
91
+ fn=None,
92
+ inputs=[text_output],
93
+ 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(); }"
94
+ )
95
+
96
+ clear_btn.click(
97
+ clear_all,
98
+ inputs=[],
99
+ outputs=[image_input, text_output, char_count, word_count, status]
100
+ )
101
+
102
+ # Example images
103
+ gr.Markdown("""
104
+ ### πŸ“Έ Try with example images
105
+ Upload any image with text, or try these examples:
106
+ - Receipts
107
+ - Business cards
108
+ - Book pages
109
+ - Signs
110
+ """)
111
 
112
  if __name__ == "__main__":
113
+ demo.launch(server_name="0.0.0.0", server_port=7860)