mertcobanov commited on
Commit
fde3eae
0 Parent(s):

Duplicate from deprem-ml/deprem-ocr

Browse files
Files changed (6) hide show
  1. .gitignore +160 -0
  2. README.md +13 -0
  3. app.py +141 -0
  4. openai_api.py +30 -0
  5. requirements.txt +5 -0
  6. utils.py +35 -0
.gitignore ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Deprem OCR
3
+ emoji: 👀
4
+ colorFrom: green
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 3.17.0
8
+ app_file: app.py
9
+ pinned: true
10
+ duplicated_from: deprem-ml/deprem-ocr
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from easyocr import Reader
2
+ import gradio as gr
3
+ import openai
4
+ import ast
5
+ import os
6
+
7
+ from openai_api import OpenAI_API
8
+ import utils
9
+
10
+
11
+ openai.api_key = os.getenv("API_KEY")
12
+ reader = Reader(["tr"])
13
+
14
+
15
+ def get_text(input_img):
16
+ result = reader.readtext(input_img, detail=0)
17
+ return " ".join(result)
18
+
19
+
20
+ # Submit button
21
+ def get_parsed_address(input_img):
22
+
23
+ address_full_text = get_text(input_img)
24
+ return openai_response(address_full_text)
25
+
26
+
27
+ # Open API on change
28
+ def text_dict(input):
29
+ eval_result = ast.literal_eval(input)
30
+ utils.write_db(eval_result)
31
+
32
+ return (
33
+ str(eval_result["city"]),
34
+ str(eval_result["distinct"]),
35
+ str(eval_result["neighbourhood"]),
36
+ str(eval_result["street"]),
37
+ str(eval_result["address"]),
38
+ str(eval_result["tel"]),
39
+ str(eval_result["name_surname"]),
40
+ str(eval_result["no"]),
41
+ )
42
+
43
+
44
+ def openai_response(ocr_input):
45
+ prompt = f"""Tabular Data Extraction You are a highly intelligent and accurate tabular data extractor from
46
+ plain text input and especially from emergency text that carries address information, your inputs can be text
47
+ of arbitrary size, but the output should be in [{{'tabular': {{'entity_type': 'entity'}} }}] JSON format Force it
48
+ to only extract keys that are shared as an example in the examples section, if a key value is not found in the
49
+ text input, then it should be ignored. Have only city, distinct, neighbourhood,
50
+ street, no, tel, name_surname, address Examples: Input: Deprem sırasında evimizde yer alan adresimiz: İstanbul,
51
+ Beşiktaş, Yıldız Mahallesi, Cumhuriyet Caddesi No: 35, cep telefonu numaram 5551231256, adim Ahmet Yilmaz
52
+ Output: {{'city': 'İstanbul', 'distinct': 'Beşiktaş', 'neighbourhood': 'Yıldız Mahallesi', 'street': 'Cumhuriyet Caddesi', 'no': '35', 'tel': '5551231256', 'name_surname': 'Ahmet Yılmaz', 'address': 'İstanbul, Beşiktaş, Yıldız Mahallesi, Cumhuriyet Caddesi No: 35'}}
53
+ Input: {ocr_input}
54
+ Output:
55
+ """
56
+
57
+ openai_client = OpenAI_API()
58
+ response = openai_client.single_request(prompt)
59
+ resp = response["choices"][0]["text"]
60
+ print(resp)
61
+ resp = eval(resp.replace("'{", "{").replace("}'", "}"))
62
+ resp["input"] = ocr_input
63
+ dict_keys = [
64
+ "city",
65
+ "distinct",
66
+ "neighbourhood",
67
+ "street",
68
+ "no",
69
+ "tel",
70
+ "name_surname",
71
+ "address",
72
+ "input",
73
+ ]
74
+ for key in dict_keys:
75
+ if key not in resp.keys():
76
+ resp[key] = ""
77
+ return resp
78
+
79
+ def ner_response(ocr_input):
80
+ API_URL = "https://api-inference.huggingface.co/models/deprem-ml/deprem-ner"
81
+ headers = {"Authorization": "Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}
82
+
83
+ def query(payload):
84
+ response = requests.post(API_URL, headers=headers, json=payload)
85
+ return response.json()
86
+
87
+ output = query({
88
+ "inputs": ocr_input,
89
+ })
90
+ return output
91
+
92
+ # User Interface
93
+ with gr.Blocks() as demo:
94
+ gr.Markdown(
95
+ """
96
+ # Enkaz Bildirme Uygulaması
97
+ """
98
+ )
99
+ gr.Markdown(
100
+ "Bu uygulamada ekran görüntüsü sürükleyip bırakarak AFAD'a enkaz bildirimi yapabilirsiniz. Mesajı metin olarak da girebilirsiniz, tam adresi ayrıştırıp döndürür. API olarak kullanmak isterseniz sayfanın en altında use via api'ya tıklayın."
101
+ )
102
+ with gr.Row():
103
+ img_area = gr.Image(label="Ekran Görüntüsü yükleyin 👇")
104
+ ocr_result = gr.Textbox(label="Metin yükleyin 👇 ")
105
+ open_api_text = gr.Textbox(label="Tam Adres")
106
+ submit_button = gr.Button(label="Yükle")
107
+ with gr.Column():
108
+ with gr.Row():
109
+ city = gr.Textbox(label="İl")
110
+ distinct = gr.Textbox(label="İlçe")
111
+ with gr.Row():
112
+ neighbourhood = gr.Textbox(label="Mahalle")
113
+ street = gr.Textbox(label="Sokak/Cadde/Bulvar")
114
+ with gr.Row():
115
+ tel = gr.Textbox(label="Telefon")
116
+ with gr.Row():
117
+ name_surname = gr.Textbox(label="İsim Soyisim")
118
+ address = gr.Textbox(label="Adres")
119
+ with gr.Row():
120
+ no = gr.Textbox(label="Kapı No")
121
+
122
+ submit_button.click(
123
+ get_parsed_address,
124
+ inputs=img_area,
125
+ outputs=open_api_text,
126
+ api_name="upload_image",
127
+ )
128
+
129
+ ocr_result.change(
130
+ openai_response, ocr_result, open_api_text, api_name="upload-text"
131
+ )
132
+
133
+ open_api_text.change(
134
+ text_dict,
135
+ open_api_text,
136
+ [city, distinct, neighbourhood, street, address, tel, name_surname, no],
137
+ )
138
+
139
+
140
+ if __name__ == "__main__":
141
+ demo.launch()
openai_api.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import os
3
+
4
+ class OpenAI_API:
5
+ def __init__(self):
6
+ self.openai_api_key = ""
7
+
8
+ def single_request(self, address_text):
9
+
10
+ openai.api_type = "azure"
11
+ openai.api_base = "https://damlaopenai.openai.azure.com/"
12
+ openai.api_version = "2022-12-01"
13
+ openai.api_key = os.getenv("API_KEY")
14
+
15
+ response = openai.Completion.create(
16
+ engine="Davinci-003",
17
+ prompt=address_text,
18
+ temperature=0.9,
19
+ max_tokens=256,
20
+ top_p=1.0,
21
+ n=1,
22
+ logprobs=0,
23
+ echo=False,
24
+ stop=None,
25
+ frequency_penalty=0,
26
+ presence_penalty=0,
27
+ best_of=1,
28
+ )
29
+
30
+ return response
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ openai
2
+ Pillow
3
+ easyocr
4
+ gradio
5
+ deta
utils.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import csv
3
+ import json
4
+ from deta import Deta
5
+ import os
6
+
7
+
8
+ def preprocess_img(inp_image):
9
+ gray = cv2.cvtColor(inp_image, cv2.COLOR_BGR2GRAY)
10
+ gray_img = cv2.bitwise_not(gray)
11
+ return gray_img
12
+
13
+ def save_csv(mahalle, il, sokak, apartman):
14
+ adres_full = [mahalle, il, sokak, apartman]
15
+
16
+ with open("adress_book.csv", "a", encoding="utf-8") as f:
17
+ write = csv.writer(f)
18
+ write.writerow(adres_full)
19
+ return adres_full
20
+
21
+
22
+ def get_json(mahalle, il, sokak, apartman):
23
+ adres = {"mahalle": mahalle, "il": il, "sokak": sokak, "apartman": apartman}
24
+ dump = json.dumps(adres, indent=4, ensure_ascii=False)
25
+ return dump
26
+
27
+
28
+ def write_db(data_dict):
29
+ # 2) initialize with a project key
30
+ deta_key = os.getenv('DETA_KEY')
31
+ deta = Deta(deta_key)
32
+
33
+ # 3) create and use as many DBs as you want!
34
+ users = deta.Base("deprem-ocr")
35
+ users.insert(data_dict)