RufusRubin777 commited on
Commit
1a287cf
1 Parent(s): a6afa92

Delete app_1.py

Browse files
Files changed (1) hide show
  1. app_1.py +0 -158
app_1.py DELETED
@@ -1,158 +0,0 @@
1
- import gradio as gr
2
- import spaces
3
- from transformers import AutoModel, AutoTokenizer
4
- import os
5
- import base64
6
- import io
7
- import uuid
8
- import time
9
- import shutil
10
- from pathlib import Path
11
- import re
12
- import easyocr
13
-
14
- # OCR Model
15
- tokenizer = AutoTokenizer.from_pretrained('RufusRubin777/GOT-OCR2_0_CPU', trust_remote_code=True, device_map='cpu')
16
- model = AutoModel.from_pretrained('RufusRubin777/GOT-OCR2_0_CPU', trust_remote_code=True, low_cpu_mem_usage=True, device_map='cpu', use_safetensors=True)
17
- model = model.eval().cpu()
18
- reader = easyocr.Reader(['hi'])
19
-
20
- UPLOAD_FOLDER = "./uploads"
21
- RESULTS_FOLDER = "./results"
22
-
23
- for folder in [UPLOAD_FOLDER, RESULTS_FOLDER]:
24
- if not os.path.exists(folder):
25
- os.makedirs(folder)
26
-
27
- def image_to_base64(image):
28
- buffered = io.BytesIO()
29
- image.save(buffered, format="PNG")
30
- return base64.b64encode(buffered.getvalue()).decode()
31
-
32
- # OCR Processing of the image uploaded by the user
33
- # @spaces.GPU
34
- def run_GOT(image,language):
35
- unique_id = str(uuid.uuid4())
36
- image_path = os.path.join(UPLOAD_FOLDER, f"{unique_id}.png")
37
-
38
- shutil.copy(image, image_path)
39
-
40
- try:
41
- if language == "English":
42
- res = model.chat(tokenizer, image_path, ocr_type='ocr')
43
- return res
44
- elif language == "Hindi":
45
- res = reader.readtext(image)
46
- extracted_text = ''
47
- for x in res:
48
- extracted_text += x[1] + '\n'
49
- return extracted_text
50
- else:
51
- english_extraction = model.chat(tokenizer, image_path, ocr_type='ocr')
52
- hindi_extraction = reader.readtext(image)
53
- hindi_extract = ''
54
- for x in hindi_extraction:
55
- hindi_extract += x[1] + '\n'
56
- return english_extraction+'\n'+hindi_extract
57
- except Exception as e:
58
- return f"Error: {str(e)}", None
59
- finally:
60
- if os.path.exists(image_path):
61
- os.remove(image_path)
62
-
63
- # Search Functionality
64
- def search_keyword(text,keyword):
65
- # Convert text and keyword to lowercase for case-insensitive search
66
- text_lower = text.lower()
67
- keyword_lower = keyword.lower()
68
-
69
- # Keyword position in the text
70
- pos = text_lower.find(keyword_lower)
71
-
72
- if pos == -1:
73
- ans = '<h3 style="text-align: center;">'+"Keyword not found"+'</h3>'
74
- else:
75
- res = [i.start() for i in re.finditer(keyword_lower, text)]
76
- ans = '<h3>'
77
- l = 0
78
- for x in res:
79
- ans += text[l:x]+'<mark>'+text[x:x+len(keyword)]+'</mark>'
80
- l += len(text[l:x]+text[x:x+len(keyword)])
81
- ans += text[l:]+'</h3>'
82
- return ans
83
-
84
- def cleanup_old_files():
85
- current_time = time.time()
86
- for folder in [UPLOAD_FOLDER, RESULTS_FOLDER]:
87
- for file_path in Path(folder).glob('*'):
88
- if current_time - file_path.stat().st_mtime > 3600: # 1 hour
89
- file_path.unlink()
90
-
91
- title_html = """
92
- <h1> <span class="gradient-text" id="text">Scan Master</span></h1>
93
- <p>Scan Master uses General OCR Theory (GOT), a 580M end-to-end OCR 2.0 model for English optical character recognition and EASYOCR for Hindi optical character recognition. It supports plain text ocr.</p>
94
- """
95
-
96
- # acknowledgement_html = """
97
- # <h3>Acknowledgement</h3>
98
- # <a href="https://huggingface.co/ucaslcl/GOT-OCR2_0">[😊 Hugging Face]</a>
99
- # <a href="https://arxiv.org/abs/2409.01704">[📜 Paper]</a>
100
- # <a href="https://github.com/Ucas-HaoranWei/GOT-OCR2.0/">[🌟 GitHub]</a>
101
- # """
102
-
103
- # aboutme_html = """
104
- # <h3>About Me</h3>
105
- # <p>Name : Satvik Chandrakar</p>
106
- # <a href="https://github.com/Satvik-ai">[🌟 GitHub]</a> """
107
-
108
-
109
- # Scan Master web application developed using Gradio
110
- with gr.Blocks() as scan_master_web_app:
111
- gr.HTML(title_html)
112
- gr.Markdown("""
113
- You need to upload your image below and choose appropriate language, then click "Submit" to run the model. More characters will result in longer wait times.""")
114
-
115
- with gr.Row():
116
- with gr.Column():
117
- image_input = gr.Image(type="filepath", label="Upload your image")
118
- gr.Markdown("""If your image contains only English text, then choose English option in the language. If it contains only Hindi text, then choose Hindi option in the language. If it contains both the language, then choose the third option.""")
119
- lang_dropdown = gr.Dropdown(
120
- choices=[
121
- "English",
122
- "Hindi",
123
- "English + Hindi",
124
- ],
125
- label="Choose language",
126
- value="English"
127
- )
128
- submit_button = gr.Button("Submit")
129
-
130
- with gr.Column():
131
- ocr_result = gr.Textbox(label="GOT output")
132
-
133
- with gr.Row():
134
- with gr.Column():
135
- keyword = gr.Textbox(label="Search a keyword in the extracted text")
136
- search_button = gr.Button("Search")
137
-
138
- with gr.Column():
139
- search_result = gr.HTML(label="Search result")
140
-
141
- # gr.HTML(acknowledgement_html)
142
- # gr.HTML(aboutme_html)
143
-
144
- submit_button.click(
145
- run_GOT,
146
- inputs=[image_input,lang_dropdown],
147
- outputs=[ocr_result]
148
- )
149
-
150
- search_button.click(
151
- search_keyword,
152
- inputs=[ocr_result,keyword],
153
- outputs=[search_result]
154
- )
155
-
156
- if __name__ == "__main__":
157
- cleanup_old_files()
158
- scan_master_web_app.launch()