Rohit56negi commited on
Commit
baffc82
·
verified ·
1 Parent(s): ee14e01

Upload 3 files

Browse files
OCR-and-Keyword-Search-with-Qwen2-VL/README.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hindi English OCR with Keyword Search using Qwen2-VL
2
+
3
+ ![{60950997-B613-4DCA-A2F0-AF993237BDE1}](https://github.com/user-attachments/assets/3c742784-509b-4198-8e91-75d19b519f9f)
4
+
5
+ This project implements a powerful OCR tool that utilizes the **Qwen2-VL** model for extracting text from images in Hindi and English. Users can upload images, extract the text, and optionally search for specific keywords within the extracted text.
6
+
7
+ ## Features
8
+
9
+ - Upload images with text in Hindi or English.
10
+ - Extracted text displayed in a user-friendly interface.
11
+ - Optional keyword search functionality to highlight occurrences in the extracted text.
12
+
13
+ ## Requirements
14
+
15
+ Before running the application, ensure you have the following Python packages installed:
16
+
17
+ ```bash
18
+ pip install gradio transformers Pillow torch
19
+
20
+ ```
21
+ Usage
22
+ Clone the repository:
23
+ ```
24
+ git clone https://github.com/Ashutosh0x/OCR-and-Keyword-Search-with-Qwen2-VL.git
25
+ cd OCR-and-Keyword-Search-with-Qwen2-VL
26
+ ```
27
+
28
+ Install the required packages.
29
+
30
+ Run the application:
31
+ python app.py
32
+
33
+ How It Works
34
+ The application uses the Qwen2-VL model to perform OCR on uploaded images.
35
+ Users can select a language for the OCR process and enter keywords for searching within the extracted text.
36
+ The app provides instant feedback and displays both the extracted text and search results.
37
+ Model
38
+ This application utilizes the Qwen2-VL model, which is designed for visual-language tasks, enabling efficient text extraction and processing from images.
39
+
40
+ Gradio for the easy-to-use interface.
41
+ Transformers library for model handling.
42
+ Pillow for image processing.
43
+
44
+ Deploying on Hugging Face
45
+ You can easily deploy this application on Hugging Face Spaces. Follow these steps:
46
+
47
+ Go to Hugging Face Spaces.
48
+ Create a new Space and choose the "Gradio" option.
49
+ Upload your app.py file and any other necessary files (like requirements.txt).
50
+ Once uploaded, Hugging Face will automatically build and run your application.
OCR-and-Keyword-Search-with-Qwen2-VL/app.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
3
+ from PIL import Image
4
+ import torch
5
+ import re
6
+
7
+ # Load the Qwen2-VL model and processor
8
+ model = Qwen2VLForConditionalGeneration.from_pretrained(
9
+ "Qwen/Qwen2-VL-2B-Instruct", torch_dtype="auto", device_map={"": "cpu"}
10
+ )
11
+ processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct")
12
+
13
+ # Function to perform OCR using Qwen2-VL
14
+ def ocr_image(image, language):
15
+ try:
16
+ # Prepare the input format for Qwen2-VL
17
+ messages = [
18
+ {
19
+ "role": "user",
20
+ "content": [
21
+ {"type": "image", "image": image},
22
+ {"type": "text", "text": "Extract the text from this image."},
23
+ ],
24
+ }
25
+ ]
26
+
27
+ # Process the input for the model
28
+ text_input = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
29
+ inputs = processor(images=image, text=[text_input], padding=True, return_tensors="pt").to("cpu")
30
+
31
+ # Generate text using the model
32
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
33
+ extracted_text = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
34
+
35
+ return extracted_text
36
+ except Exception as e:
37
+ return f"Error occurred during OCR: {str(e)}"
38
+
39
+ # Function to perform keyword search within the extracted text
40
+ def search_text(text, keyword):
41
+ if not text:
42
+ return "No text extracted."
43
+
44
+ # Search for keyword occurrences (case insensitive)
45
+ keyword_pattern = re.compile(re.escape(keyword), re.IGNORECASE)
46
+ matches = keyword_pattern.findall(text)
47
+
48
+ if matches:
49
+ # Highlight all matches in the text by wrapping them with ** for bold
50
+ highlighted_text = re.sub(keyword_pattern, f"**{keyword}**", text)
51
+ return highlighted_text
52
+ else:
53
+ return "Keyword not found in the text."
54
+
55
+ # Function to handle both OCR and search functionality
56
+ def process_image(image, language, keyword=""):
57
+ extracted_text = ocr_image(image, language)
58
+
59
+ if keyword:
60
+ result_text = search_text(extracted_text, keyword)
61
+ else:
62
+ result_text = extracted_text
63
+
64
+ return extracted_text, result_text
65
+
66
+ # Gradio Interface
67
+ def build_interface():
68
+ with gr.Blocks() as interface:
69
+ gr.Markdown("## Hindi & English OCR with Keyword Search using Qwen2-VL")
70
+ gr.Markdown("Upload an image with text in Hindi or English, extract the text, and optionally search for keywords within it.")
71
+
72
+ with gr.Row():
73
+ with gr.Column(scale=1):
74
+ image_input = gr.Image(type="pil", label="Upload an Image", elem_id="image-input", height=400)
75
+
76
+ with gr.Column(scale=1):
77
+ # Dropdown for selecting language (currently not used by Qwen2-VL, but kept for future expansion)
78
+ language_input = gr.Dropdown(label="Select Language for OCR", choices=["English", "Hindi", "Both"], value="Both", elem_id="lang-dropdown", interactive=True)
79
+
80
+ keyword_input = gr.Textbox(label="Enter Keyword to Search (Optional)", value="", placeholder="Enter keyword here", elem_id="keyword-input", interactive=True)
81
+
82
+ with gr.Row():
83
+ text_output = gr.Textbox(label="Extracted Text", interactive=False, placeholder="Extracted text will appear here.", elem_id="text-output", lines=10)
84
+ search_output = gr.Textbox(label="Search Results", interactive=False, placeholder="Search results will appear here.", elem_id="search-output", lines=10)
85
+
86
+ # Button to submit the image, language, and keyword
87
+ submit_btn = gr.Button("Process", elem_id="submit-btn")
88
+
89
+ # Markdown for feedback during processing
90
+ processing_message = gr.Markdown("Processing...", visible=False, elem_id="processing-message")
91
+
92
+ def on_submit(image, language, keyword):
93
+ if not image:
94
+ return "No image provided", "Please upload an image.", gr.update(visible=False)
95
+
96
+ # Display the processing message
97
+ extracted_text, result_text = process_image(image, language, keyword)
98
+ return extracted_text, result_text, gr.update(visible=False)
99
+
100
+ # Connect the button to the function with inputs and outputs
101
+ submit_btn.click(on_submit,
102
+ inputs=[image_input, language_input, keyword_input],
103
+ outputs=[text_output, search_output, processing_message])
104
+
105
+ return interface
106
+
107
+ # Main function to launch the app
108
+ if __name__ == "__main__":
109
+ interface = build_interface()
110
+ interface.launch(share=True, inbrowser=True, debug=True, height=900, width=1600)
OCR-and-Keyword-Search-with-Qwen2-VL/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio
2
+ transformers
3
+ torch
4
+ Pillow
5
+ regex
6
+ accelerate>=0.26.0