File size: 7,915 Bytes
4f01ba7 818b7e0 f14e62a 36af98d 1c5c566 818b7e0 4f01ba7 45c6498 4f01ba7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 |
import streamlit as st
import os
from PIL import Image, ImageOps
from PIL import ImageDraw, ImageFont
import random
from io import BytesIO
from requests.auth import HTTPBasicAuth
import boto3
import json
from datetime import datetime
import requests
remote_url = os.environ.get("remote_url")
base_url = os.environ.get("base_url")
authEmail = os.environ.get("authEmail")
authPass = os.environ.get("authPass")
aws_access_key_id = os.environ.get("AWS_ACCESS_KEY_ID")
aws_secret_access_key = os.environ.get("AWS_SECRET_ACCESS_KEY")
aws_default_region = os.environ.get("AWS_DEFAULT_REGION")
bucket_name = os.environ.get("bucket_name")
user_id = os.environ.get("user_id")
# Read values from the JSON file
# with open('../config.json') as f:
# config = json.load(f)
# remote_url = config.get("remote_url")
# base_url = config.get("base_url")
# authEmail = config.get("authEmail")
# authPass = config.get("authPass")
# aws_access_key_id = config.get("AWS_ACCESS_KEY_ID")
# aws_secret_access_key = config.get("AWS_SECRET_ACCESS_KEY")
# aws_default_region = config.get("AWS_DEFAULT_REGION")
# bucket_name = config.get("bucket_name")
# user_id = config.get("user_id")
# Create a Boto3 session
session = boto3.Session(
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
region_name=aws_default_region
)
# Create an S3 client
s3 = session.client('s3')
def calculate_font_size(box, max_font_size=30, min_font_size=10, font_path="NotoSansKR-Medium.otf"):
width = box[2] - box[0]
font_size = int(max_font_size * width / 100)
# Limit font size to max and min values
font_size = min(max_font_size, font_size)
font_size = max(min_font_size, font_size)
font = ImageFont.truetype(font_path, font_size)
return font, font_size
def estimate_text_size(text, font_size):
# Estimate text width based on number of characters and average character width
avg_character_width = font_size * 0.5 # Adjust this value based on your font and preferences
text_width = len(text) * avg_character_width
# Estimate text height based on font size
text_height = font_size
return text_width, text_height
def draw_annotated_box(draw, box, text, font_path="NotoSansKR-Medium.otf"):
x1, y1, x2, y2 = box
draw.rectangle([x1, y1, x2, y2], outline="green", width=3)
# Calculate font size and get font
font, font_size = calculate_font_size(box)
# Measure text size
text_width, text_height = estimate_text_size(text, font_size)
# Reduce height of the background box by a factor (for example, 0.8 for 80% of the original height)
reduced_text_height = int(text_height * 0.8)
# Draw white background for text
background_box = [x1, y1 - reduced_text_height - 2, x1 + text_width + 2, y1]
draw.rectangle(background_box, fill="green")
# Draw text
draw.text((x1, y1 - text_height), text, font=font, fill="white")
def upload_to_s3(image_data, region):
# Pre-configured bucket name and path
region = region.upper()
path_prefix = f"image_{region}"
# S3 client setup
s3 = boto3.client('s3')
# Generating file name based on current date and time
now = datetime.now()
date_str = now.strftime("%Y%m%d")
time_str = now.strftime("%H%M%S")
file_name = f"{path_prefix}/{user_id}_{date_str}_{time_str}.jpeg"
try:
# Attempt to upload the image to S3
s3.put_object(
Body=image_data,
Bucket=bucket_name,
Key=file_name,
ContentType='image/jpeg'
)
return True
except Exception as e:
# Log and return False if an error occurs
print(f"Error uploading to S3: {e}")
return False
def main():
st.title("๐ ANPR - Ver.1.0.leon")
country = st.radio("๐ฆ Type of License", options=['Korean', 'EU'])
st.markdown("""
Korean : ๐ฐ๐ท<br>
EU : ๐ฆ๐ฑ ๐ฆ๐ฉ ๐ฆ๐น ๐ง๐ช ๐ง๐ฆ ๐ง๐ฌ ๐ญ๐ท ๐จ๐พ ๐จ๐ฟ ๐ฉ๐ฐ ๐ซ๐ฎ ๐ซ๐ท ๐ฉ๐ช ๐ฌ๐ท ๐ญ๐บ ๐ฎ๐ช ๐ฎ๐น ๐ฑ๐ฎ ๐ฒ๐น ๐ฒ๐จ ๐ฒ๐ช ๐ณ๐ฑ ๐ฒ๐ฐ ๐ณ๐ด ๐ต๐ฑ ๐ต๐น ๐ท๐ด ๐ธ๐ฒ ๐ท๐ธ ๐ธ๐ฐ ๐ธ๐ฎ ๐ช๐ธ ๐ธ๐ช ๐จ๐ญ ๐ฌ๐ง ๐ฑ๐บ
""", unsafe_allow_html=True)
st.text("")
st.write("๐งช Options ")
use_default_image = st.checkbox("Use default server image?", value=False) # New checkbox
img_file_buffer = st.file_uploader("๐ฆ Upload your image", type=['jpg', 'jpeg', 'png']) if not use_default_image else None
submit = st.button("Submit")
show_image = True
if show_image:
font = ImageFont.truetype("NotoSansKR-Medium.otf", 30)
if submit:
if use_default_image or img_file_buffer is not None:
gif_runner = st.image('wait-waiting.gif')
if use_default_image:
# Load the default image from your server here
# Make sure to replace 'your_default_image_path' with the actual path
if country == 'Korean':
image_choice = random.choice(['kr1.jpg'])
image_choice = os.path.join('./', image_choice)
image = Image.open(image_choice)
elif country == 'EU':
image_choice = random.choice(['eu1.jpg'])
image_choice = os.path.join('./', image_choice)
image = Image.open(image_choice)
else:
image = Image.open(img_file_buffer)
image = ImageOps.exif_transpose(image)
img_byte_arr = BytesIO()
if image.mode == 'RGBA':
rgb_image = image.convert('RGB')
rgb_image.save(img_byte_arr, format='JPEG')
else:
image.save(img_byte_arr, format='JPEG')
img_byte_arr.seek(0)
region = "kr"
if country == 'Korean':
region = "kr"
elif country == 'EU':
region = "eu"
auth_values = HTTPBasicAuth(authEmail, authPass)
# Make POST request
url = remote_url
form_data = {'base_url': base_url, 'region':region}
files = {'file': ('image.jpg', img_byte_arr, 'image/jpeg')}
res = requests.post(url, headers={'Accept': 'application/json'},
files=files,
data=form_data, # Additional form data
auth=auth_values)
img_byte_arr.seek(0)
if use_default_image == False:
if upload_to_s3(img_byte_arr.getvalue(), region):
print("Upload successful!")
# Close the file
img_byte_arr.close()
if res.status_code == 200:
output_res = res.json()
if show_image:
draw = ImageDraw.Draw(image)
for item in output_res['results']:
x1, y1, x2, y2 = item['ltrb']
ocr_text = item['ocr']
# print(x1,y1,x2,y2,ocr_text)
if show_image:
draw_annotated_box(draw, (x1, y1, x2, y2), ocr_text)
if show_image:
st.image(image, caption='Annotated Image', use_column_width=True)
st.header('๐ฆ Result Json')
st.code(json.dumps(output_res, indent=4, ensure_ascii=False), language="json")
else:
error_detail = res.json().get("detail", "Unknown error")
st.code(f"Failed to get result, Status Code: {res.status_code}, Detail: {error_detail}")
gif_runner.empty()
st.write("")
if __name__ == "__main__":
#main function
main()
|