sberbank-ai commited on
Commit
67f47a5
1 Parent(s): 3827361

feat: Add app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -0
app.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.system("pip install git+https://github.com/ai-forever/ReadingPipeline")
3
+
4
+ import cv2
5
+ import json
6
+
7
+ import gradio as gr
8
+ from huggingface_hub import hf_hub_download
9
+
10
+ from ocrpipeline.predictor import PipelinePredictor
11
+ from ocrpipeline.linefinder import get_structured_text
12
+
13
+
14
+ def get_config_and_download_weights(repo_id, device='cpu'):
15
+ # download weights and configs
16
+ pipeline_config_path = hf_hub_download(repo_id, "pipeline_config.json")
17
+ ocr_model_path = hf_hub_download(repo_id, "ocr/ocr_model.ckpt")
18
+ ocr_config_path = hf_hub_download(repo_id, "ocr/ocr_config.json")
19
+ segm_model_path = hf_hub_download(repo_id, "segm/segm_model.ckpt")
20
+ segm_config_path = hf_hub_download(repo_id, "segm/segm_config.json")
21
+
22
+ # change paths to downloaded weights and configs in main pipeline_config
23
+ with open(pipeline_config_path, 'r') as f:
24
+ pipeline_config = json.load(f)
25
+ pipeline_config['main_process']['SegmPrediction']['model_path'] = segm_model_path
26
+ pipeline_config['main_process']['SegmPrediction']['config_path'] = segm_config_path
27
+ pipeline_config['main_process']['SegmPrediction']['device'] = device
28
+ pipeline_config['main_process']['OCRPrediction']['model_path'] = ocr_model_path
29
+ pipeline_config['main_process']['OCRPrediction']['config_path'] = ocr_config_path
30
+ pipeline_config['main_process']['OCRPrediction']['device'] = device
31
+
32
+ # save pipeline_config
33
+ with open(pipeline_config_path, 'w') as f:
34
+ json.dump(pipeline_config, f)
35
+
36
+ return pipeline_config_path
37
+
38
+
39
+ def predict(image_path):
40
+ image = cv2.imread(image_path)
41
+ rotated_image, pred_data = PREDICTOR(image)
42
+ structured_text = get_structured_text(pred_data, ['shrinked_text'])
43
+
44
+ result_text = ''
45
+ for page_text in structured_text:
46
+ for line_text in page_text:
47
+ result_text += ' '.join(line_text) + '\n'
48
+ return result_text
49
+
50
+
51
+ PIPELINE_CONFIG_PATH = get_config_and_download_weights("sberbank-ai/ReadingPipeline-Peter")
52
+
53
+ PREDICTOR = PipelinePredictor(pipeline_config_path=PIPELINE_CONFIG_PATH)
54
+
55
+ gr.Interface(
56
+ predict,
57
+ inputs=gr.Image(label="Upload an image", type="filepath"),
58
+ outputs=gr.Textbox(label="Text on the image"),
59
+ title="Text on the image",
60
+ ).launch()