mertcobanov's picture
sucess button added
3c61664
raw
history blame contribute delete
No virus
5.79 kB
import streamlit as st
from PIL import ImageFilter, Image
from easyocr import Reader
import numpy as np
import os
from openai_api import OpenAI_API
from deta import Deta # Import Deta
import time
from datetime import datetime
reader = Reader(["tr"])
def get_text(input_img):
# img = Image.fromarray(input_img)
detailed = np.asarray(input_img.filter(ImageFilter.DETAIL))
result = reader.readtext(detailed, detail=0, paragraph=True)
return " ".join(result)
def openai_response(ocr_input):
prompt = f"""Tabular Data Extraction You are a highly intelligent and accurate tabular data extractor from
plain text input and especially from emergency text that carries address information, your inputs can be text
of arbitrary size, but the output should be in [{{'tabular': {{'entity_type': 'entity'}} }}] JSON format Force it
to only extract keys that are shared as an example in the examples section, if a key value is not found in the
text input, then it should be ignored. Have only city, distinct, neighbourhood,
street, no, tel, name_surname, address Examples:
Input: Deprem sırasında evimizde yer alan adresimiz: İstanbul, Beşiktaş, Yıldız Mahallesi, Cumhuriyet Caddesi No: 35, cep telefonu numaram 5551231256, adim Ahmet Yilmaz
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'}}
Input: 5.29 PMO $ 0 87 DEVREMİZ ÖZGÜR ORÇAN ARKADAŞIMIZA ULAŞAMIYORUZ BEYOĞLU MAH FEVZİ ÇAKMAK CAD. NO.58-TÜRKOĞLUI KAHRAMANMARAŞ 5524357578 AdReSe YaKIN OLANLAR VEYA ULASANLAR LÜTFEN BiLGILENDIRSIN .
Output: {{'city': 'Kahramanmaraş', 'distinct': 'Türkoğlu', 'neighbourhood': 'Beyoğlu Mahallesi', 'street': 'Çakmak Caddesi', 'no': '58', 'tel': '5524357578', 'name_surname': 'Özgür Orçan', 'address': 'Beyoğlu Mahallesi, Çakmak Caddesi, No:58 Türkoğlu/Kahramanmaraş'}}
Input: Ahmet @ozknhmt Ekim 2021 tarihinde katıldı - 2 Takipçi Takip ettiğin kimse takip etmiyor AKEVLER MAH. 432SK RÜYA APT ANT(BEDİİ SABUNCU KARŞISI) ANTAKYA HATAY MERVE BELANLI ses veriyor ancak hiçbiryardım ekibi olmadığı için kurtaramryoruz içeri girip, lütfen acil yardım_ İsim: Merve Belanlı tel 542 757 5484 Ö0 12.07
Output: {{'city': 'Hatay', 'distinct': 'Antakya', 'neighbourhood': 'Akevler Mahallesi', 'street': '432 Sokak', 'no': '', 'tel': '5427575484', 'name_surname': 'Merve Belanlı', 'address': 'Akevler Mahallesi, 432 Sokak, Rüya Apt. Antakya/Hatay'}}
Input: 14:04 Sümerler Cemil Şükrü Çolokoğlu ilköğretim okulu karşısı 3 9öçük altında yardım bekyouk Lütfen herkes paylogsın
Output: {{'city': '', 'distinct': '', 'neighbourhood': 'Sümerler Mahallesi', 'street': 'Cemil Şükrü Çolokoğlu İlköğretim Okulu Karşısı', 'no': '', 'tel': '', 'name_surname': '', 'address': 'Sümerler Mahallesi, Cemil Şükrü Çolokoğlu İlköğretim Okulu Karşısı'}}
Input: {ocr_input}
Output:
"""
openai_client = OpenAI_API()
response = openai_client.single_request(prompt)
resp = response["choices"][0]["text"]
print(resp)
resp = eval(resp.replace("'{", "{").replace("}'", "}"))
# resp["input"] = ocr_input
# dict_keys = [
# "city",
# "distinct",
# "neighbourhood",
# "street",
# "no",
# "tel",
# "name_surname",
# "address",
# "input",
# ]
# for key in dict_keys:
# if key not in resp.keys():
# resp[key] = ""
return resp
def write_db(data_dict):
# 2) initialize with a project key
deta_key = os.getenv("DETA_KEY")
deta = Deta(deta_key)
# 3) create and use as many DBs as you want!
users = deta.Base("new-data")
users.insert(data_dict)
print("Pushed to db")
# Add file uploader to allow users to upload photos
uploaded_file = st.file_uploader("", type=["jpg", "png", "jpeg"])
resp = None
# Add 'before' and 'after' columns
if uploaded_file is not None:
img = Image.open(uploaded_file)
print(type(img))
col1, col2 = st.columns([0.5, 0.5])
with col1:
st.markdown('<p style="text-align: center;">Before</p>', unsafe_allow_html=True)
st.image(img, width=300)
with st.spinner("OCR Processing"):
st.header("Output Text")
ocr_output = get_text(img)
st.write(ocr_output)
with st.spinner("Waiting response from OpenAI"):
resp = openai_response(ocr_output)
st.write(resp)
with st.form("my_form", clear_on_submit=True):
st.write("Inside the form")
resp["timestamp"] = time.time()
resp["datetime"] = str(datetime.now())
city_box = st.text_input(label="Il", value=resp["city"])
distinct_box = st.text_input(label="Ilce", value=resp["distinct"])
neighbourhood_box = st.text_input(label="Mahalle", value=resp["neighbourhood"])
street_box = st.text_input(label="Sokak", value=resp["street"])
no_box = st.text_input(label="No", value=resp["no"])
tel_box = st.text_input(label="Tel", value=resp["tel"])
name_surname_box = st.text_input(
label="Isim Soyisim", value=resp["name_surname"]
)
address_box = st.text_input(label="Adres", value=resp["address"])
form_button = st.form_submit_button("Gonder")
if form_button:
write_db(resp)
st.success('Veri kaydedildi.')