Manogari2003 commited on
Commit
20a47d9
·
verified ·
1 Parent(s): 9c3a023

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -0
app.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image
3
+ from byaldi import RAGMultiModalModel
4
+ from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
5
+ from qwen_vl_utils import process_vision_info
6
+ import torch
7
+
8
+ # Load models colpali
9
+ def load_models():
10
+ RAG = RAGMultiModalModel.from_pretrained("vidore/colpali")
11
+ model = Qwen2VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-2B-Instruct",
12
+ trust_remote_code=True, torch_dtype=torch.float32) # float32 for CPU
13
+ processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", trust_remote_code=True)
14
+ return RAG, model, processor
15
+
16
+ RAG, model, processor = load_models()
17
+ # Function for OCR and search
18
+ def ocr_and_search(image, keyword):
19
+ text_query = "Extract all the text in Hindi and English from the image."
20
+
21
+ messages = [
22
+ {
23
+ "role": "user",
24
+ "content": [
25
+ {"type": "image", "image": image},
26
+ {"type": "text", "text": text_query},
27
+ ],
28
+ }
29
+ ]
30
+
31
+ text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
32
+ image_inputs, video_inputs = process_vision_info(messages)
33
+ inputs = processor(
34
+ text=[text],
35
+ images=image_inputs,
36
+ videos=video_inputs,
37
+ padding=True,
38
+ return_tensors="pt",
39
+ ).to("cpu")
40
+
41
+ # Generate text
42
+ with torch.no_grad():
43
+ generated_ids = model.generate(**inputs, max_new_tokens=2000)
44
+ generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
45
+
46
+ # Decode output while avoiding any coordinate information
47
+ extracted_text = processor.batch_decode(
48
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=True
49
+ )[0]
50
+ extracted_text = extracted_text.replace("The text in the image is:", "").strip()
51
+ # Filter out any unwanted text (like coordinates)
52
+ extracted_text = ' '.join(filter(lambda x: not any(char.isdigit() for char in x), extracted_text.split()))
53
+
54
+ # Separate English and Hindi text using a simple heuristic
55
+ english_text = ' '.join(filter(lambda x: all((char.islower() or char.isupper()) or char == "'" for char in x), extracted_text.split()))
56
+ hindi_text = ' '.join(filter(lambda x: any(ord(char) >= 128 for char in x), extracted_text.split()))
57
+
58
+ # Perform keyword search
59
+ keyword_lower = keyword.lower().strip()
60
+ matched_keywords = []
61
+ if keyword_lower:
62
+ if keyword_lower in extracted_text.lower():
63
+ matched_keywords = [keyword]
64
+
65
+ # Prepare plain text output
66
+ plain_text_output = (
67
+ f"- English: {' '.join(english_text.split()) if english_text else 'No English text found.'}\n\n"
68
+ f"- Hindi: {' '.join(hindi_text.split()) if hindi_text else 'No Hindi text found.'}"
69
+ )
70
+
71
+ return extracted_text, matched_keywords, plain_text_output
72
+
73
+ # Gradio App function
74
+ def app(image, keyword):
75
+ # Call OCR and search function
76
+ extracted_text, matched_keywords, plain_text_output = ocr_and_search(image, keyword)
77
+
78
+ # Format search results
79
+ search_results_str = "\n".join(matched_keywords) if matched_keywords else "No matches found for the keyword."
80
+
81
+ return extracted_text, search_results_str, plain_text_output
82
+
83
+ # Gradio Interface
84
+ iface = gr.Interface(
85
+ fn=app,
86
+ inputs=[
87
+ gr.Image(type="pil", label="Upload an Image"),
88
+ gr.Textbox(label="Enter keyword to search in extracted text", placeholder="Keyword")
89
+ ],
90
+ outputs=[
91
+ gr.Textbox(label="Extracted Text"),
92
+ gr.Textbox(label="Search Results"),
93
+ gr.Textbox(label="Plain Text Output", lines=10) # For plain text output
94
+ ],
95
+ title="Optical Character Recognition with Keyword Search from Images",
96
+ )
97
+
98
+ # Launch Gradio App
99
+ iface.launch()