amoldwalunj commited on
Commit
7902e1a
1 Parent(s): 38ad06f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -0
app.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytesseract
2
+ from PIL import Image
3
+ import pandas as pd
4
+ import os
5
+ import gradio as gr
6
+ import numpy as np
7
+ import gradio as gr
8
+
9
+
10
+ def ocr_df_using_pytesseract(image):
11
+ pytesseract.pytesseract.tesseract_cmd =r"C:\Users\amold\Desktop\Upwork\pdf to image and pytesseract\tesseact_exe\Tesseract-OCR\tesseract.exe"
12
+
13
+ #image = Image.open(example['image_path'])
14
+
15
+ width, height = image.size
16
+
17
+ # apply ocr to the image
18
+ ocr_df = pytesseract.image_to_data(image, output_type='data.frame')
19
+ float_cols = ocr_df.select_dtypes('float').columns
20
+ ocr_df = ocr_df.dropna().reset_index(drop=True)
21
+ ocr_df[float_cols] = ocr_df[float_cols].round(0).astype(int)
22
+ ocr_df = ocr_df.replace(r'^\s*$', np.nan, regex=True)
23
+ ocr_df = ocr_df.dropna().reset_index(drop=True)
24
+
25
+ ocr_df
26
+
27
+ ocr_df['X1']=ocr_df['left']
28
+
29
+ ocr_df['Y1']=ocr_df['top']
30
+
31
+ ocr_df['X2']= ocr_df['left'] + ocr_df['width']
32
+
33
+ ocr_df['Y2']= ocr_df['top'] + ocr_df['height']
34
+
35
+ return ocr_df
36
+
37
+
38
+ def image_to_text(image):
39
+ ocr_df= ocr_df_using_pytesseract(image)
40
+
41
+
42
+ grouped_text = ocr_df.groupby(['block_num', 'line_num'])['text'].agg(' '.join).reset_index()
43
+
44
+ # sort the text by line numbers within each block
45
+ grouped_text = grouped_text.sort_values(['block_num', 'line_num'])
46
+
47
+ # join the text by blocks and add newlines
48
+ result = ''
49
+ for i, row in grouped_text.iterrows():
50
+ if i > 0 and row['block_num'] != grouped_text.loc[i-1, 'block_num']:
51
+ result += '\n\n'
52
+ result += row['text'].rstrip() + '\n'
53
+
54
+ return result
55
+
56
+
57
+
58
+ demo = gr.Interface(fn=image_to_text,
59
+ inputs= gr.Image(type="pil"),
60
+ outputs=["text"],
61
+ title="Menu image to text",
62
+ description= "Upload Menu image here")
63
+ demo.launch(share=True)